简体   繁体   English

通过回调更新父组件状态后,无法更新子组件状态

[英]Unable to update child component state after updating parent component state through callback

I am trying to update the state of the parent component through a callback in the onPress function of a child component and then update the state of the child component itself. 我正在尝试通过子组件的onPress函数中的回调来更新父组件的状态,然后更新子组件本身的状态。 However, I am only able to either update state of the parent component or the child component but not both in sequence. 但是,我只能更新父组件或子组件的状态,而不能同时更新两个组件的状态。 The code concerning my issue is listed below: 有关我的问题的代码如下:

 export default class GameScreen extends React.Component { constructor (props) { super(props); this.state = { nextOne: 'X' } this.nextOneCallback = this.nextOneCallback.bind(this); } nextOneCallback () { this.setState({ nextOne: 'Y' }); } render() { const ticTacToeSquare = []; for (let i = 0; i < 3; i++) { const rowArray = []; for (let j = 0; j < 3; j++) { const newBox = (<TicTacToeBox key = {Math.random(10000)} callback={this.nextOneCallback}/>); rowArray.push(newBox); } const eachRenderedRow = ( <View key = {Math.random(10000)} style={{flexDirection: 'row'}}> {rowArray} </View> ); ticTacToeSquare.push(eachRenderedRow); } return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> {ticTacToeSquare} <Button title="Home" onPress={() => this.props.navigation.navigate('Home')} /> </View> ); } } class TicTacToeBox extends React.Component{ constructor(props) { super(props); this.state = { text: '', } } render () { return ( <View style={{ borderColor: 'black', borderWidth: 2, alignItems: 'center', justifyContent: 'center'}} > <Text style={{textAlign: 'center', height: 40, width: 40}} maxLength={1} onPress={ () => { this.setState((prevState, props) => ({text: 'X'})); // this.props.callback(); } }> {this.state.text} </Text> </View> ); } } 

The onPress function of the TicTacToeBox does not behave as expected. TicTacToeBox的onPress函数的行为不符合预期。 Any help on how I can update the parent state and then the child state will be deeply appreciated. 对于如何更新父状态然后子状态的任何帮助,将深表感谢。 Thanks in advance! 提前致谢!

Pass the value you want to update to child also 也将您要更新的值传递给子级

<TicTacToeBox key = {Math.random(10000)} callback={this.nextOneCallback}  nextOne={this.state.nextOne}/>);

then extract this value in child using props 然后使用道具在孩子中提取该值

this.props.nextOne in the child this.props.nextOne中的this.props.nextOne

So whenever you will hit the callback function from child the value will get updated in both parent and child. 因此,每当您从子项中调用回调函数时,父项和子项中的值都会得到更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM