2つの子コンポーネントを持つ親コンポーネントがあります。ボタンクリックアクションは、状態の親コンポーネントを変更する必要があり、それは両方の子コンポーネントに影響するはずです。子コンポーネントの親コンポーネントの状態を変更し、その状態をプロパティとして渡し、子コンポーネントの状態を変更します。
これは私の親コンポーネントです:
export default class SearchView extends React.Component {
// attributes
state = {
loading: false
}
//
constructor(props){
super(props)
}
// get list of items
getItems(){
this.setState({loading:true})
axios.get('/path_to_data').then(response => {
this.setState({items:response.data, loading: false})
}).catch(err=>{console.log(err)})
}
render(){
return (
<div>
<SearchForm
getItems={this.getItems.bind(this)}
loading={this.state.loading}
/>
{ this.state.items ? <ItemCards items={this.state.items} /> : "No data"}
</div>
)
}//render
}//class
これは、クリックイベントが発生した私のコンポーネントである:
export default class SearchForm extends React.Component {
// attributes
state = {
loading: this.props.loading
}
// render
render(){
return (
<Segment inverted color="yellow">
<Grid columns="2">
<Grid.Column>
</Grid.Column>
<Grid.Column>
<Button
loading={this.state.loading}
disabled={this.state.loading}
color="black"
onClick={this.props.getItems}
>
Search
</Button>
</Grid.Column>
</Grid>
</Segment>
)
}//render
}//class SearchForm
、これは他の子要素である:
export default class ItemCards extends React.Component {
// constructor
constructor(props){
super(props)
}
// state
state = {
items: this.props.items
}
...
問題がありますボタンをクリックすると、状態オブジェクトの変更がloading
属性が変更されるため、イベントがトリガーされた同じ子コンポーネントにプロパティが渡されます。そして、私はこの子コンポーネントが親の状態が変更され、そのプロパティが変更されたことを検出すると期待しています、そして、それはそれ自身の状態を変更し、UIは応答が来るまで要素にloading
属性をレンダリングします(応答が来たら、 。
なぜこのコードは期待どおりに機能しませんか?どうすれば修正できますか?
ありがとうございます、これは良い説明です! – Kunok