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

标签 javascript reactjs

我有以下 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/

相关文章:

javascript - Eval 真的给 JavaScript 引入了动态作用域吗?

javascript - .map 中的嵌入函数用于访问映射信息

javascript - 如何使用 moment.js 从日期列表中获取最小或最大日期?

reactjs - 使用 React、Typescript 和 ES6 进行 Jest 测试

javascript - AngularJS - 具有循环表值的动态表行和列

javascript - string.charAt(x) 还是 string[x]?

javascript - MomentJS 获取具有可变一周第一天的周数

javascript - Node.js - 提取部分 URL

reactjs - 在 TabNavigator 中隐藏标签 - ReactNavigation

node.js - 如何使用api从数据库中获取数据?