gpt4 book ai didi

javascript - 从 child 更改 parent 的状态并在另一个 child react native 中使用它

转载 作者:行者123 更新时间:2023-11-28 18:20:38 26 4
gpt4 key购买 nike

我需要从子组件B更改父组件A的状态,并在另一个子组件中使用该更新状态父组件 A 的 >C 。我做了以下事情。我可以从子组件更新父组件,但第二个子组件仍然获取父组件的旧状态。那么这里出了什么问题呢?

组件 A 有 B、C 子组件。 (这里,A也是某人的 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>);
}
}

从 A 的子组件 B 中,我想通过回调函数更改 A 的 state.name 。确实如此(经过测试)

 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 的 state.name 也作为 prop 传递给 A 的另一个子组件 C。当我从 B 更改 A 的 state.name 后,我需要从组件 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>);
}
}

}

最佳答案

您需要使用C类中的componentWillReceiveProps函数。使用此方法,您可以根据更新的 props 来更新 C 类。

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

关于javascript - 从 child 更改 parent 的状态并在另一个 child react native 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39969423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com