在使用 redux-saga 进行多次连续状态更改后,React-redux 连接函数无法将状态映射到道具

React-redux connect function can't map state to props after multiple consecutive state changes using redux-saga

我有一个简单的减速器:

// reducer.js
const itemId = (state = "", action) => {
  if (action.type === SET_ID) {
    console.log("reducer updated");
    return action.payload.id;
  }
  else {
    return state;
  }
};

一个组件连接到商店:

const Component = ({ itemId }) => {
  console.log("Component rendered");
  return <div> {itemId}</div>;
};

const mapStateToProps = state => ({
  itemId: state.itemId
});

export const ConnectedComponent = connect(mapStateToProps)(Component);

还有一个包含三个动作的 saga,其中第一个和最后一个动作具有相同的负载:

const createSetIdAction = id => ({
  type: SET_ID,
  payload: {
    id
  }
});

export const saga = function*() {
  yield put(createSetIdAction("FirstID"));
  yield put(createSetIdAction("SecondID"));
  yield put(createSetIdAction("FirstID"));
};

调度这些动作时,reducer 会连续更新三次,每个动作一次。这意味着状态已经改变,每个连接的组件都应该反映这种变化。

问题是我的组件没有像我预期的那样被重新渲染 3 次。也许是因为 mapStateToProps 太慢而无法注意到状态变化,或者当它注意到状态变化时,它包含与以前相同的值,因此不会呈现任何东西。

当我添加一个小的延迟(在我的浏览器中超过大约 35 毫秒)时,一切都开始工作:

// saga
  yield put(createSetIdAction("First_ID"));
  yield delay(35);
  yield put(createSetIdAction("Second_ID"));
  yield put(createSetIdAction("First_ID"));

组件按预期呈现。

有没有办法让连接函数在每次状态更新后渲染组件,而无需在 saga 中使用 delay

工作sandbox here

我是 Redux 维护者。

React-Redux 不保证您的 UI 代码将 运行 用于每个分派的动作。它仅保证它将 运行 与商店中的 最新 值。

这是由于 React-Redux 如何管理对商店的订阅和传播更新,以及 React 批处理如何重新呈现。