reactjs - 为什么 React 在 parent 之前渲染 child ?

我是 React 的新手,我已经遇到过几次这个问题。子组件依赖于它们的父组件来获得某些 Prop ,但出于某种原因,React 会在它们的父组件之前渲染其中的许多子组件,从而造成空操作。我不明白为什么 React 会这样做,有人可以解释为什么会这样吗?

例子:

在 App.jsx 中我有:

<div className='container'>
    {this.state.loggedIn ? this.changeView() : <Landing />}
</div>

在 render() 中,因此一旦用户登录,就会触发 changeView,返回 <GroceryList user={this.state.user} /> .这调用:

const GroceryList = (props) => (
  <div>
    <AddIngredients ingredients={props.user.groceryList} />
  </div>
);

然后调用其子 AddIngredients,它依赖于 props.ingredients 在以下代码中呈现:

const IngredientList = [];

  for(let i=0; i<this.props.ingredients.length; i++) {
    IngredientList.push(<Ingredient
      key={i}
      index={i}
      value={this.props.ingredients[i]}
      handleDeleteIngredient={this.handleDeleteIngredient}
      handleUpdateIngredient={this.handleUpdateIngredient}
    />);
  }

当我第一次登录应用程序时,出现错误 Uncaught TypeError: Cannot read property 'length' of undefined但如果我刷新页面,它就会工作。

最佳答案

问题不是你在问题中提到的。问题是您在尚未加载时访问“groceryList”的长度。您可以使用安全导航方法解决此问题,也可以像下面这样解决:

const GroceryList = (props) => (
  <div>
    {props.user.groceryList && <AddIngredients ingredients={props.user.groceryList} />}
  </div>
);

但是,根据您的代码和偏好,您可以使用多种语法。

https://stackoverflow.com/questions/48131464/

相关文章:

java - 将原始类型传递给 JAX RS POST

r - 在 igraph 中绘制适合度分布的幂律

tensorflow - 将 Keras 与 TensorFlow 后端一起使用时,如何禁用 cuD

julia - 如何以编程方式从 Julia 中的字符串标识符定义变量?

r - 根据两个坐标之间的最近距离对矩阵进行排序

reactjs - 如何用 React 组件替换 Markdown 渲染的 HTML 标签?

jenkins - 在领域中使用唯一凭据 - Jenkins 本地实例

php - Laravel Dusk 测试 click() 不工作

powerbi - power bi 中的计算列不更新结果

c++ - 是否有必要在 std::coroutine_handle 上调用 destroy?