親反応コンポーネントにアイテムのリストがあり、新しいアイテムと更新アイテムが追加されています。子コンポーネントは小道具内のアイテムを受け取り、それをレンダリングします。親コンポーネントが反応で配列を更新しているときに、子コンポーネントが更新されない
親状態が更新されると、子コンポーネントはその値を更新していません。 "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