1
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)
}
pnkz
  • 326
  • 4
  • 20

1 Answers1

2

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})
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • someMethod () { return this.props.x + this.props.y } i am trying to access props form a method. There the x and y value are not updated. Getting the previous value. – pnkz Jun 10 '17 at 06:14
  • any idea why the props are not getting updated for component B. The solution is work around or the only solution? – pnkz Jun 10 '17 at 06:35
  • The thing is componentWillReceive Props is called with the updated props and if you directly call someMethod() from this function, someMethod cannot get access to the new props unless you explicitly pass it the new props which I have done. So the above solution in not a workaround but a proper solution – Shubham Khatri Jun 10 '17 at 06:38
  • In that case, componentWillReceiveProps (nextProps) { this.props = nextProps; this.setState({z: someMethod}) } Is this right? – pnkz Jun 10 '17 at 06:43
  • componentWillReceiveProps (nextProps) { this.constructor(nextProps); } Can I invoke the constructor again from componentWillReceiveProps. – pnkz Jun 10 '17 at 07:12
  • No, you shouldn't, you should call a custom function – Shubham Khatri Jun 10 '17 at 07:15