Я новичок в React и пытаюсь написать программу, в которой я создал 3 компонента: Таблица, Заголовок таблицы и Тело таблицы и включил заголовок таблицы и Тело таблицы в таблицу.Я пытаюсь передать данные из App.js, используя состояние, и пытаюсь отобразить их в компонент таблицы.Я не получаю никакой ошибки, но не получаю желаемого результата.
Вот снимок экрана вывода инструментов React dev:
Здесь показано, что состояние имеет значения :
![Here it shows that state has values](https://i.stack.imgur.com/Xl6B3.png)
Здесь показано, что он пуст, поэтому данные не передаются, я думаю :
![Here it shows that its empty so data is not being passed I guess](https://i.stack.imgur.com/f7Rq0.png)
App.js:
import React, { Component } from 'react';
import './App.css';
import Table from './Table';
class App extends Component {
/*You can think of state as any data that should be saved and modified
without necessarily being added to a database – for example,
adding and removing items from a shopping cart before confirming your purchase.*/
state={
characters:[
{
'id':1,
'name':'Smit',
'job':'Student'
},
{
'id':2,
'name':'Tom',
'job':'Teacher'
},
{
'id':3,
'name':'Hardee',
'job':'Friend'
},
{
'id':4,
'name':'Dom',
'job':'Principal'
},
{
'id':5,
'name':'Dik',
'job':'Cleaner'
}
]
};
//to remove any data field from table using state
removeCharacter = index => {
//console.log(this.state);
const { characters } = this.state;
//console.log(characters);
//to update the state if data is modified
this.setState({
characters: characters.filter((character, i) => {
return i !== index;
})
});
}
render() {
//declared characters which will contains data to be insterted into table
const characters=[];
return (
<div className="container">
{/*Need to pass the character into table so passing it through charData variable into Table component */}
<Table characterData={characters}
removeCharacter={this.removeCharacter}
/>
</div>
);
}
}
export default App;
Table.js
import React, { Component } from 'react';
class Table extends Component {
render() {
const { characterData, removeCharacter } = this.props;
return (
<table>
<TableHeader />
<TableBody
characterData={characterData}
removeCharacter={removeCharacter}
/>
</table>
);
}
}
const TableHeader = () => {
return (
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Job</th>
</tr>
</thead>
);
}
const TableBody = props => {
//passing the props through as a parameter,
//and map through the array to return a table row for each object(element) in the array.
//This map will be contained in the rows variable, which we’ll return as an expression.
const rows = props.characterData.map((row, index) => {
return (
<tr key={index}>
<td>{row.id}</td>
<td>{row.name}</td>
<td>{row.job}</td>
<td><button onClick={() => props.removeCharacter(index)}>Delete</button></td>
</tr>
);
});
return <tbody>{rows}</tbody>;
}
export default Table;