2017-01-04 42 views
0

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属性をレンダリングします(応答が来たら、 。

なぜこのコードは期待どおりに機能しませんか?どうすれば修正できますか?

答えて

1

この例では、<Button>コンポーネントは状態を持たず、代わりに小道具を使用してください。

そうに書き換えてみてください。

<Button 
    loading={this.props.loading} 
    disabled={this.props.loading} 
    color="black" 
    onClick={this.props.getHotels}> 

理由が反応して、あなたは別のコンポーネントから状態を渡さないということです。状態とは、個々のコンポーネントに含まれるものです。良いパターンは、親コンポーネントが状態を保持し、小道具を介して子どもと通信することです。

+0

ありがとうございます、これは良い説明です! – Kunok

関連する問題