首页 > 解决方案 > 反应状态没有从不同的调用中更新

问题描述

在使用反应的记忆游戏项目中,我试图在游戏结束时使用一个按钮创建弹出窗口,引导您进入下一个级别(更多卡片)。为了创建下一个级别,我使用了初始化状态的 resetGame 函数。属性“isFinished”影响弹出窗口是否显示。

如果我按下重置按钮 - 没有问题。如果我按下下一级按钮 - 状态中的所有属性都会初始化,除了 isFinished 并且弹出窗口仍然存在。如您所见,resetGame 是从重置按钮和 FinishPopup 组件中调用的。

render() { 
        return ( 
            <div style={boardStyle}>
                <h1 style={titleStyle}>Memory Game</h1>
                <Timer reset={this.state.resetRequest} />
                <div>
                    <Button onClick={()=>this.resetGame(rowsVar,columnsVar)} type="button" className="btn btn-secondary">Reset</Button>
                </div>
                <div style={cardWrapper}>
                   {this.renderBoard()}
                   {this.checkIfGameOver()}
                   {this.state.isFinished ? (<FinishPopup nextLevel={()=>this.resetGame(rowsVar+1,columnsVar+1)} />) : null }
                </div>
            </div>
        );
    }

这是 resetGame 函数:

resetGame=(rows,columns)=>{
    rowsVar=rows;
    columnsVar=columns;
    let newState = Object.assign({},this.state);
    newState.board = this.initialBoard(rows,columns);
    newState.numOfOpenCars = 0;
    newState.lastId="";
    newState.isFinished=false; //this is the property that does not changing
    newState.matchCounter=0;
    this.setState(newState);
}

这是弹出渲染功能:

render() { 
    return ( 

    <div style={popupStyle}>
        <div>
            <h1>
                Well done!!
            </h1>
            <button onClick={this.props.nextLevel}>Next Level</button> 
        </div>
    </div>);
}

我究竟做错了什么?

标签: reactjspropertiespopupsetstate

解决方案


推荐阅读