我的作业项目的快速总结。
我的后端有一个 REST API,它有一个 API 方法从外部 API 返回星球大战 Angular 色。
在我的 Web 开发中,我尝试从 REST API 获取这些数据,我可以看到数据实际上显示在浏览器开发人员工具中,但我收到另一个错误。
“警告:index.js:1437 警告:函数作为 React 子项无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者您可能打算调用此函数而不是返回它。”
您能看看下面的 .js 文件出了什么问题吗?
import React, {Component} from "react";
import {Table,} from 'react-bootstrap'
const urlCharacters = 'URL WORKS - BUT NOT SHOWING HERE.';
class Characters extends Component {
constructor(props) {
super(props);
this.state = {characters: []}
;
}
async componentDidMount() {
//async fetchCharactersFromBackend(){
const res = await fetch(urlCharacters);
const data = await res.json();
console.log(data);
const newData = data.map(e => JSON.parse(e.name));
this.setState([newData]);
}
render() {
if (!this.state.characters) {
return null
}
return (
<div>
<h2>Persons table</h2>
<Table striped bordered hover>
<thead>
<tr>
<th>Character Name</th>
</tr>
</thead>
<tbody>
{this.renderCharacters}
</tbody>
</Table>;
</div>
);
}
renderCharacters(characters) {
characters.forEach(e => {
return ("<tr><td>" + e.name + "</td></tr>")
});
}
}
/*
Persons = () => {
return (
<div>
<h2>Persons table</h2>
<Table striped bordered hover>
<thead>
<tr>
<th>Character Name</th>
</tr>
</thead>
<tbody>
{this.renderCharacters}
</tbody>
</Table>;
</div>
);
};
*/
export default Characters;
最佳答案
执行以下修复并让我知道它是否有效:
this.setState([newData]); --> this.setState({characters: newData})
{this.renderCharacters} --> {this.renderCharacters()}
将 renderCharacters 更新为以下内容:
renderCharacters() {
return this.state.characters.map(e => {
return ("<tr><td>" + e.name + "</td></tr>")
});
}
}
关于javascript - 函数作为 react 子项无效? - 需要帮助将获取的数据提取到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55892132/