我有一个我在渲染方法中渲染的项目列表(方便,实际上命名为 Item)。
render() {
return (
<div>
{
this.state.items.map(item => (
<Item
id={item.id}
myValue={item.myValue}
updateItem={this.handleUpdateItem}
deleteItem={this.handleDeleteItem}
/>
))
}
</div>
)
}
这有效,但我收到警告Each child in a list should have a unique "key" prop
. 但是,添加 key 道具会导致错误。
render() {
return (
<div>
{
this.state.items.map(item => (
<Item
id={item.id}
key={item.id}
myValue={item.myValue}
updateItem={this.handleUpdateItem}
deleteItem={this.handleDeleteItem}
/>
))
}
</div>
)
}
错误:
Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {myValue}). If you meant to render a collection of children, use an array instead.
此错误仅在更新时发生,当我更改项目的 myValue 时。初始页面加载得很好。
有人可以帮助我了解这里发生了什么吗?
所以当我运行你的代码时,完整的错误文本是:
Objects are not valid as a React child (found: object with keys {myValue}). If you meant to render a collection of children, use an array instead.
in div (created by Item)
in div (created by Item)
in Item (created by ItemList)
in div (created by ItemList)
in ItemList (created by App)
in div (created by App)
in App
使用堆栈跟踪,我们可以看到这是在Item
组件内引起的。更进一步,这是在两个div
s内结束的代码:
let display =
<div>
{this.state.displayValue}
<button onClick={this.handleEdit}>Edit</button>
<button onClick={this.handleDelete}>Delete</button>
</div>
的渲染this.state.displayValue
导致错误。使用console.log,它显示更新后,displayValue
设置为一个对象。
我会让你追问为什么会这样:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句