簡體   English   中英

通過回調更新父組件狀態后,無法更新子組件狀態

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

我正在嘗試通過子組件的onPress函數中的回調來更新父組件的狀態,然后更新子組件本身的狀態。 但是,我只能更新父組件或子組件的狀態,而不能同時更新兩個組件的狀態。 有關我的問題的代碼如下:

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

TicTacToeBox的onPress函數的行為不符合預期。 對於如何更新父狀態然后子狀態的任何幫助,將深表感謝。 提前致謝!

也將您要更新的值傳遞給子級

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

然后使用道具在孩子中提取該值

this.props.nextOne中的this.props.nextOne

因此,每當您從子項中調用回調函數時,父項和子項中的值都會得到更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM