我是 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/