2017-09-14 40 views
0

我在反应新的,可能做错了什么。反应变化道具海量错误

我有一个主父组件和他的孩子和孩子主要的儿童(儿童2)的。

main-> child1->子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>' 

我该如何正确更改它?由于

回答

0

您不能更新道具,它们是不可变的。如果你想在你最父操纵结果值,而其在child1的搜索方法,将其移动到父,赶上结果搜索方法有 -

父 -

<child1 items={this.state.lst} getData={this.search.bind(this)}> 

Child1 -

<Find dataChild2={this.props.items} findData={this.props.getData.bind(this)}/> 

CHILD2 -

someFunc(){ 
this.props.findData(result); 
} 
+1

谢谢,这对我的作品。 – Redair

1

你不能做到这一点:

this.props.items=res; 

道具和统计信息是不可变对象。只需在组件状态内创建一个新项目:

this.setState({newItems: res}); 
... 
<Find dataChild2={this.state.items} findData={this.search.bind(this)}/>