[英]Change state in parent component from child, then pass that state as property and change state in child component
我有一个带有两个子组件的父组件。 单击按钮的操作应更改状态父组件,这将影响两个子组件。
这是我的父组件:
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
属性,直到响应到来(当响应到来时,删除加载) 。
为什么此代码无法按预期工作? 我如何解决它?
在此示例中, <Button>
组件不应具有任何状态,而应仅使用props。
因此,尝试重写为:
<Button
loading={this.props.loading}
disabled={this.props.loading}
color="black"
onClick={this.props.getHotels}>
原因是在进行响应时,您不会将状态从一个组件传递到另一个组件。 状态是包含在单个组件中的东西。 父组件保留状态并通过道具与子组件进行通信是一个很好的模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.