首页 > 解决方案 > 如何在 React 中使用单个调度来调度多个动作?

问题描述

我正在做一个项目,但仍在学习 React。所以目前,我的函数中有以下内容。有人告诉我,像这样的大量调度会导致问题,除了看起来很乱,并建议创建一个调度。我该怎么做呢?

dispatch({
      type: 'UPDATE_ARRAY',
      orderItemsArray: newitemsArray,
    });
    dispatch({
      type: 'UPDATE_NUMBER',
      tickNumber: tickNumber,
    });
    dispatch({
      type: 'UPDATE_MESSAGE',
      message: orderMessage,
    })

标签: javascriptreactjsreact-reduxreact-hooks

解决方案


使用 redux-batched-actions。

    const mapDispatchToProps = (dispatch) => ({
  action2: id => dispatch(Actions.action2(id)),
  action3: id => dispatch(Actions.action3(id)),
  action1: (dateId, attrId) =>
    dispatch(batchActions([
      Actions.action2(dateId),
      Actions.action3(attrId)
    ]))
});

当在没有任何性能优化的情况下开箱即用时,有两个主要问题: React 将重新渲染多次 React Redux 将多次重新评估选择器


推荐阅读