【问题标题】:delay on getting property, dispatch react-redux延迟获取财产,调度 react-redux
【发布时间】:2021-11-14 02:04:12
【问题描述】:

更新board组件时延迟,我的dispatch(checkResult(board));不能正常工作。井字游戏,这里有一个问题的例子:

设置了 3 个十字架但没有胜利,但是当我再做 1 个动作(设置一个十字架或零)时,则算胜利:

我的代码在:

 const mapStateToProps = ({board, players}) => ({board, players});

const mapDispatchToProps =  dispatch => ({
    draw:  (board, players, squareIndex) => {
        if (!board[squareIndex]) {
            if (players[players.turn] === 'X') {
                  dispatch(drawXAction(squareIndex));
            } else {
                  dispatch(drawOAction(squareIndex));
            }
            console.log(dispatch(checkResult(board)))

            dispatch(checkResult(board));
            dispatch(toggleTurnAction());
        }
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(Square); 

还有 checkResult 函数:

export function checkResult(board) {
    if (checkVictory(board, 'X')) {
        return {
            type: X_WINS
        }
    } else if (checkVictory(board, '0')) {
        return {
            type: O_WINS
        }
    } else {
        const check = board.filter(symbol=>symbol===null);
        if(check.length===1) {
            return {
                type: TIE
            }
        }else {
            return {
                type: 'RANDOM'
            }
        }
    }
}

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    您正在将当前的board 传递给checkResult 函数,这意味着当您的 checkResult 函数正在执行时,它没有接收到最新的板——您在前几行中更新的内容。

    redux 原则之一指出 - 它启用单一事实来源。您的代码违反了这一原则,导致了这种不一致。您需要做的是 - 在checkResult 函数中获取应用程序的最新state,而不是将board 作为参数传递。

    例如

    import store from "/path/to/store";
    
    export function checkResult() {
    
      // or something like this
      // based on what you have in your store.
      const board = store.getState().board;
    
      // your function body
    }
    

    【讨论】:

    • 谢谢,我现在才学redux,所以不是什么都懂。
    • 查看他们的教程(官方网站)。这就是你在 Redux 中需要学习的全部内容 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2015-12-29
    • 2021-10-01
    相关资源
    最近更新 更多