在 componentDidMount 中设置状态时访问 React 中已定义对象的 属性 时出错

Error on accessing property of defined object in React when state is set in componentDidMount

我想弄清楚如何将道具传递给与特定路线匹配的组件。从下面的代码中可以看出,每次用户点击 /items/:id 时,我都会从 url 中获取 id,并希望使用该 id 获取访问数组的正确项目。

<Route exact path="/items/:id" render={(props) => {
    let itemId = parseInt(props.location.pathname.replace('/items/', ''));
       console.log(this.state.items[itemId].description);
       return <ItemDetail item={this.state.items[itemId]} />;

问题是,如果我 运行 这段代码,React 将崩溃并返回愤怒的红色 cannot read property description of undefined,但是——这就是我完全困惑的地方——如果我尝试记录 this.state.items[itemId] 我可以在控制台中看到完整的对象。如果我将 item 作为道具传递并尝试从子组件 ItemDetail.

中获取描述,自然会发生完全相同的事情

你现在需要,我目前正在使用简单的

componentDidMount生命周期方法中设置数据
 componentDidMount() {
    this.setState({
      items: data
    });
  }

和 React 中断,但如果我将其更改为即将弃用的 componentWillMount 应用程序 运行 应该如此,我不明白为什么。如果在安装后设置了状态并且我知道该项目存在于数组中因为我可以记录它,为什么我不能读取其中的属性?

由于 componentDidMount 中似乎是同步设置状态,您可以安全地将其移至构造函数以避免错误

constructor(props) {
    super(props);
    this.state = {
         items: data
     }
}

如果数据来自 API 调用,那么您需要在 componentDidMount 中进行 API 调用并将状态设置为 onsuccess 或 onerror 回调并提供条件检查何时在渲染中使用状态值

return <ItemDetail item={this.state.items? this.state.items[itemId] : {}} />;

或显示加载,直到 API 调用成功

render() {
   if(!this.state.items) {
       return <div>Loading...</div>
   }
   return <Route exact path="/items/:id" render={(props) => {
    let itemId = parseInt(props.location.pathname.replace('/items/', ''));
       console.log(this.state.items[itemId].description);
       return <ItemDetail item={this.state.items[itemId]} />;
}