我有父項組件中的項目列表,並且在其中添加了新項目和更新項目。子組件將接收道具中的物品並進行渲染。父組件正在更新其數組時,父組件未更新
當父狀態得到更新時,子組件未更新其值。 我是否需要更新「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>;
}
}
爲什麼你的孩子有自己的國家呢? – azium