【问题标题】:Change state in parent component from child, then pass that state as property and change state in child component从子组件更改父组件中的状态,然后将该状态作为属性传递并更改子组件中的状态
【发布时间】:2017-05-18 05:00:18
【问题描述】:

我有一个带有两个子组件的父组件。一个按钮点击动作应该改变父组件的状态并且应该影响两个子组件。

这是我的父组件:

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 属性,直到响应到来(当响应到来时,加载是删除)。

为什么这段代码没有按预期工作?我如何解决它?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    在这个例子中,&lt;Button&gt; 组件不应该有任何状态,而是使用 props 代替。

    所以尝试重写为:

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

    原因是在反应中,您不会将状态从一个组件传递到另一个组件。状态是包含在单个组件中的东西。一个好的模式是让父组件保持状态,并通过 props 与子组件通信。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      • 1970-01-01
      • 2016-12-21
      • 2016-12-26
      • 2019-07-12
      • 2021-06-08
      相关资源
      最近更新 更多