我用reactjs开发了一个表,我想获取数据并将其显示在此表上。
数据显示在控制台上,但未显示在表上。
我的代码是:
constructor(props){
super(props);
this.state = {
categories: [],
file:''};
this.onchange = this.onchange.bind(this)
this.handleAdd = this.handleAdd.bind(this);
}
componentDidMount() {
axios({
method: 'get',
url: 'http://172.16.234.24:8000/api/allCategories',
headers: {
'Cors-Allow-Credentials':true,
'Access-Control-Allow-Credentials':true,
'Access-Control-Allow-Origin': '172.16.234.24:8000',
'Access-Control-Allow-Headers':'Content-Type,
Authorisation',
'Content-Type': 'multipart/form-data'
}
}).then(response => {
try { if (response && response.data) {
this.setState({ categories: response.data});
console.log(response)
}
console.log(this.state.categories)
}
catch(error)
{console.log('noo')}
}).catch(error => console.log(error));
}
handleAdd() {
try {
console.log("Add Categorie")
this.props.history.push('/addcategorie');
}
catch (error) {
this.setState({ error });
}
}
render() {
let {
categories
} = this.state;
return (
<div>
<Table><thead><tr>
<th scope="col">Name</th>
<th scope="col">Photo</th>
</tr>
</thead>
<tbody>{categories.length && this.state.categories.map(categorie => (
<tr key={categorie.id}>
<td>{categorie.name}</td>
<td>{categorie.file}</td>
</tr>
))} </tbody>
</Table>
</div>
当我运行它时,我得到
index.js:1446 Warning: validateDOMNesting(...): Text nodes cannot appear as a child of <tbody>.
并在控制台上获得数据,但是我的表是空的。如何解决?
最佳答案
您在tbody起始标记和结束标记之间有一些空格
只需按原样替换以下代码,然后尝试
<tbody>{categories.length && categories.map(categorie => (
<tr key={categorie.id}>
<td>{categorie.name}</td>
<td>{categorie.file}</td>
</tr>
))}</tbody>
看起来很愚蠢,但实际上是在渲染tbody和一些空格(即文本)。
更清楚一点
更改
))} </tbody>
至
))}</tbody>