我是 React 新手,可能做错了什么。
我有一个主要父组件及其子组件和主要子组件的子组件(子组件 2)。
主->子1->子2
我通过 props.items 向 child1 发送数据:
main.js
<child1 items={this.state.lst}>
然后我将其重新发送给child2:
child1.js
search(res){
this.props.items=res;
}
<Find dataChild2={this.props.items} findData={this.search.bind(this)}/>
在子 2 中,我更改了此数据并调用 child1 函数搜索:
child2.js
someFunc(){
//manipulate with this.props.dataChild2 and write it in result;
this.props.findData(result);
}
我只想在搜索功能中重写 this.props.items 但出现错误:
×
TypeError: Cannot assign to read only property 'items' of object '#<Object>'
如何正确更改它?谢谢
最佳答案
你不能这样做:
this.props.items=res;
Prop 和统计数据是不可变的对象。只需在组件的状态中创建一个新项目即可:
this.setState({newItems: res});
...
<Find dataChild2={this.state.items} findData={this.search.bind(this)}/>
关于javascript - react 改变 Prop 巨大错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46216343/