我正在尝试使用 React 与 REST API 进行交互,并且我意识到当我获取数据时,render会在没有数据的情况下调用一次,然后再使用数据调用一次。
当我尝试处理此数据时,这会引发异常,但我可以使用 if 语句来检查数据是否为空。但是,我不确定是否需要这样做。
class App extends Component {
state = {
TodoList: {},
};
componentWillMount() {
axios.get("http://localhost:5001/1").then((response) => {
this.setState({
TodoList: response.data,
});
});
}
render() {
console.log(this.state);
return <h1>hello </h1>;
}
}
Run Code Online (Sandbox Code Playgroud)
这是完全正常的。
您的App组件流程如下:
render方法来加载组件componentDidMountaxios.get哪个是异步操作this.setStateApp组件检测到状态有更新,因此执行render方法再次加载组件this.state.TodoList因此,您绝对应该处理第一次加载时发生的没有数据的情况
更新:
组件生命周期componentWillMount现已弃用,这意味着您不应再使用它。将其替换componentDidMount为。从功能上来说,它们在您的示例中应该没有区别
| 归档时间: |
|
| 查看次数: |
5825 次 |
| 最近记录: |