Component A
this.state = {
x: 1,
y: 2
}
reset () {
this.setState ({
x: 3,
y: 5
})
}
render () {
<B x = {this.state.x} y = {this.state.y} onClick = {this.reset.bind(this)}/>
}
=============================================== =========
Component B
this.state = {
z: someMethod()
}
someMethod () {
return this.props.x + this.props.y
}
On Click,我正在调用reset方法并更新组件A的状态但是如何重新呈现组件B.现在它不更新组件B.
Tried with
componentWillReceiveProps (nextProps) {
this.constructor(nextProps)
}
答案 0 :(得分:2)
setState
函数中的第二个组件也需要componentWillReceiveProps
。构造函数仅在初始渲染时调用,并且如果它依赖于道具,则不应仅在构造函数中指定状态
componentWillReceiveProps (nextProps) {
this.setState({z: nextProps.x + nextProps.y})
}
如果你想使用someMethod就像
那样someMethod(props) {
props? return props.x + props.y : return this.props.x + this.props.y
}
然后在componentWillReceiveProps
中 componentWillReceiveProps (nextProps) {
var z = someMethod(nextProps)
this.setState({z})
}