【问题标题】:How can I get rid of so many dispatches?我怎样才能摆脱这么多的调度?
【发布时间】:2021-11-16 03:41:05
【问题描述】:

在我的 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 可以帮助我吗?

【问题讨论】:

  • 你可以调度一个事件并在多个地方处理它
  • @AlexShtromberg 我该怎么做?

标签: javascript reactjs redux store dispatch


【解决方案1】:

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

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

如果您正在使用 Redux Toolkit(现在确实应该这样做),您可以使用 extraReducers

Redux 样式指南中的相关概念阅读:

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

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2022-10-18
    • 2012-12-26
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多