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



我有以下反应组件

    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>);
    }
}

我收到错误

无法读取 null 的属性"成分"。

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

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

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

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

是的,像这样初始化构造函数中的状态:

constructor(props) {
    super(props);
    this.state = {
        Ingredients: []
    };
}

Ingredients数组中有项目之前,不要呈现购物清单。

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

相关内容

  • 没有找到相关文章

最新更新