On state change of one component re-render second component

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 , I am invoking reset Method and updating the state of Component A but how to re render the component B. Now its not updating component B.

Tried with 

componentWillReceiveProps (nextProps) {

    this.constructor(nextProps)
}

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.