首页 > 解决方案 > 我怎样才能摆脱这么多的调度?

问题描述

在我的 mapDispatchToProps 中,我调用 draw ,它在按下、交叉或零时在我的正方形上绘制。现在代码如下所示:

const mapStateToProps = ({board, players}) => ({board, players});
const mapDispatchToProps =  dispatch => ({
    draw:  (board, players, squareIndex) => {
        if (!board[squareIndex]) {
            if (players[players.turn] === 'X') {
                  dispatch(drawX(squareIndex));
            } else {
                  dispatch(drawO(squareIndex));
            }

            dispatch(checkResult());
            dispatch(toggleTurn());
        }
    }
});

我想做类似的事情:

const mapDispatchToProps =  dispatch => ({
    draw
});

有可能吗?Redux-thunk 可以帮助我吗?

标签: javascriptreactjsreduxstoredispatch

解决方案


您可能应该只在此处发送一个包含所有相关信息的操作,并在多个减速器中处理该操作。即使是绘制 X 还是 O 的决定也应该发生在您的 Reducer 中,而不是在您的组件中。

只需在多个减速器中执行相同操作即可。每一个动作都会被转发给每一个reducer。

如果你正在使用 Redux Toolkit(现在你真的应该使用它),你可以使用extraReducers它。

Redux Style Guide 的相关concptual阅读:

https://redux.js.org/style-guide/style-guide/#model-actions-as-events-not-setters
https://redux.js.org/style-guide/style-guide/#allow -many-reducers-to-respond-to-the-same-action
https://redux.js.org/style-guide/style-guide/#avoid-dispatching-many-actions-sequentially


推荐阅读