gpt4 book ai didi

javascript - React js 我应该如何处理在调用 componentDidMount() 之前使用的对象?

转载 作者:行者123 更新时间:2023-11-30 21:03:06 25 4
gpt4 key购买 nike

我有以下 react 组件

    class GroceryContainer extends Component {
constructor() {
super();
debugger;
}
componentDidMount() {
fetch("http://localhost:333/Api/grocery")
.then(result=> {
return result.json();
})
.then(data =>{
debugger;
this.setState({ Ingredients: data.Ingredients })}
);
}

render() {
return (
<div>
<h2>Grocery List</h2>
<GroceryItems ingredients={this.state.Ingredients}/>
</div>);
}
}

我得到错误

Cannot read property 'Ingredients' of null.

这似乎是因为我在获取数据之前使用了 Ingredients。我该如何防止这个问题?我只是在构造函数中初始化它吗?

最佳答案

您需要在构造函数中设置默认状态:

constructor() {
super();
this.state = {
Ingredients: undefined,
};
}

注意:只能在构造函数中这样设置初始状态。所有其他本地状态更新都应该通过 this.setState

关于javascript - React js 我应该如何处理在调用 componentDidMount() 之前使用的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46921788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com