在一个组件的状态改变时重新渲染第二个组件

IT技术 javascript reactjs
2021-04-30 01:27:56
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)
}
1个回答

您也需要setStatecomponentWillReceiveProps函数中的第二个组件构造函数仅在初始渲染时调用,并且状态不应仅在构造函数中分配(如果它依赖于props)

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})
}