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
}
在 Click 上,我正在调用 reset 方法并更新组件 A 的状态,但如何重新呈现组件 B。现在它不更新组件 B。
Tried with
componentWillReceiveProps (nextProps) {
this.constructor(nextProps)
}
您也需要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})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句