【发布时间】:2017-04-17 16:15:09
【问题描述】:
我在父反应组件中有一个项目列表,我在其中添加了新项目和更新项目。子组件将接收道具中的项目并渲染它。
当父状态正在更新时,子组件不会更新其值。 我是否需要在“componentWillReceiveProps”中更新子组件状态?正确的做法是什么。
Code Example
// parent component
import React, { Component } from "react";
import TestList from '../controls/testlistview'
export default class TestView extends Component {
constructor(props) {
super();
this.state = {
items: []
};
}
render() {
return (<div>
<button onClick={this.addItem.bind(this)}> Add item</button>
<button onClick={this.changeFirstItemText.bind(this)}> Change item</button>
<TestList items={this.state.items} index={index}/>
</div>);
}
addItem() {
var items = this.state.items.map(s=> s);
items.push('new one');
this.setState({
items: items
});
}
changeFirstItemText() {
var items = this.state.items.map(s=> s);
items[0] = "changed text";
this.setState({
items: items
});
}
}
//Child component
import React, { Component } from "react";
export default class TestList extends Component {
constructor(props) {
super();
debugger;
this.state = {
rootNodes: props.items
};
}
componentWillReceiveProps(nextProps){
debugger;
}
render() {
var items = this.state.rootNodes.map((s) => {
return <div>{s}</div>;
});
return <div>{items}</div>;
}
}
【问题讨论】:
-
为什么你的孩子会有自己的状态?
标签: reactjs ecmascript-6