そのハードは、あなたの説明に基づいていますが、props
経由initial value
を通過した後、あなたのstate
内に保持された値を持つようにしようとしている場合は、ここでの例であると言うこと。あなたのfiltered values
の値は、あなたのonChangeがあなたのレンダリングやselected
内に格納して呼ばれることになるたびに更新されます。
これは、あなたの状態は子コンポーネントをレンダリングすることを許可する前に、親オブジェクトに設定されるまで、あなたは待つレンダリングで、ansychronous通話のために動作します。
someAsyncSetup() {
... doing something
this.setState({
possibleValues : possibleValues
});
}
componentDidMount()の内部では、同期可能な値の状態を設定します。値を取得したらsetState()を呼び出します。その後、インクルードは、それが子コンポーネント
{this.state.possibleValues != null &&...
<ExampleChild...
親コンプの例
constructor(props) {
super(props);
this.state = {possibleValues: null};
this.onChange = this.onChange.bind(this);
this.someAsyncSetup = this.someAsyncSetup.bind(this);
}
onChange(selected) {
this.props.onChange({ selected }); // you may need to call your parent props again
}
someAsyncSetup() {
... doing something
this.setState({
possibleValues : possibleValues
});
}
componentDidMount() {
this.someAsyncSetup(); // inside here you set your state for possible values. Then the render will wait until it is completed before creating the child component
}
{this.state.possibleValues != null &&
<ExampleChild
onChange={this.onChange}
possibleValues={this.state.possibleValues}
}
子COMPの例
class ExampleChild extends React.Component {
constructor(props) {
super(props);
this.state = { selected: this.props.filteredValues };
this.onChange = this.onChange.bind(this);
}
// onChange we want to set the list of selected values
onChange(selected) {
this.setState({ selected });
// call the parent component's onChange so that we set the values
// within the parents component state
this.props.onChange(selected);
}
render() {
return (
<someComp
options={this.props.possibleValues}
selected={this.state.selected}
defaultValue={this.props.filteredValues}
onChange={this.onChange} />
)
}
}
出典
2016-05-26 22:03:36
ALM
三素早く物事を作成する前に完了するまで待機しますレンダリング。 1.私たちが遊ぶことができるjsbinに最小の例を投稿できますか? 2.データが小道具を介して入ってくる場合、それをなぜ州に割り当てるのですか? 3.ステートが小道具に基づいており、同期している場合、それを初期化することは 'componentDidMount'ではなくコンストラクターに属します。 –
あなたはそれをせずにあなたの例を投稿することができます、それは助けが困難です。私はまた、あなたが状態を使用しようとしている場合、これはコンストラクタで行うべきだと思います。 – ALM
私はコンポーネント階層に深いので、最小限の例を作成するのは難しいようです。私は非同期的にデータをロードしていますが、それは問題でしょうか?もしそうなら、私は状態をどこで初期化すべきですか? – Akhil