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功能中也需要第二个组件。构造函数仅在初始渲染上被调用,如果状态取决于props,则不应仅在构造函数中分配状态
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}) }