【发布时间】: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