On state change of one component re-render second component

后端 未结 1 1296
挽巷
挽巷 2021-01-25 01:30
Component A
this.state = {
    x: 1,
    y: 2
}

reset () {
    this.setState ({
        x: 3,
        y: 5
    })
}


render () {
    

        
1条回答
  •  滥情空心
    2021-01-25 01:43

    You need to setState for the second component too in the componentWillReceiveProps function. Constructor is only called on intial render and state should not be only assigned in the contructor if it depends on props

    componentWillReceiveProps (nextProps) {
    
        this.setState({z: nextProps.x + nextProps.y})
    }
    

    if you want to use someMethod do it like

    someMethod(props) {
         props? return props.x + props.y : return this.props.x + this.props.y
    }
    

    and then in componentWillReceiveProps

     componentWillReceiveProps (nextProps) {
        var z = someMethod(nextProps)
        this.setState({z})
    }
    

    0 讨论(0)
提交回复
热议问题