Reputation: 401
I need to change parent component A's state from a child component B and use that updated state in another child component C of that parent component A . I did the following. I could update parent component from the child component but the second child component is still getting the old state of the parent component. So what's wrong here?
Component A has B,C childs. (here, A is also someone's child)
class A extends Component {
constructor(props) {
super(props);
});
this.state = {
name:this.props.name // first it gets name from A's parent
}
setName(UpdatedName){
this.setState({ name: UpdatedName });
}
render() {
return (
<View>
<B callBackFromA={this.setName.bind(this)}/>
<C name={this.state.name}/>
</View>);
}
}
From A's child component B, I want to change A's state.name from a call back function. And it does (tested)
class B extends Component {
constructor(props) {
super(props);
callBackFromA :this.props.callBackFromA
});
this.state = {
}
render() {
return (
<View>
<TouchableOpacity onPress={()=>this.callBackFromA('new name')}> </TouchableOpacity>
</View>);
}
}
}
A's state.name is also passed as a prop to A's another child component C. After I change A's state.name from B, then I need to save that from component C.
class C extends Component {
constructor(props) {
super(props);
});
this.state = {
name:this.props.name
}
saveData(){
//..problem is that this getting old state.name of A after B changes..
console.log(this.state.name);
}
render() {
return (
<View>
<TouchableOpacity onPress={()=>this.saveData()}> </TouchableOpacity>
</View>);
}
}
}
Upvotes: 0
Views: 1314
Reputation: 1690
you need to use componentWillReceiveProps function in C class. Using this method you can update C class according to its updated props.
componentWillReceiveProps(nextProps)
{
if(this.props.name != nextProps.name)
{
//do your task
this.setState({name:nextProps.name})
}
}
https://facebook.github.io/react/docs/component-specs.html
Upvotes: 3
Reputation: 2706
Your component C should not be using the state. State is only useful when the information needs to change from within your component, if all you need is the information passed from the component above simply point to the props.
class C extends Component {
saveData(){
console.log(this.props.name);
}
render() {
return (
<View>
<TouchableOpacity onPress={() => this.saveData()}> </TouchableOpacity>
</View>);
}
}
If you must have the property transferred to a state, then refer to Burak's answer.
Upvotes: 0