【问题标题】:React-redux connect function can't map state to props after multiple consecutive state changes using redux-saga在使用 redux-saga 进行多次连续状态更改后,React-redux 连接功能无法将状态映射到道具
【发布时间】:2020-02-26 17:27:12
【问题描述】:

我有一个简单的减速器:

// 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"));

组件按预期呈现。

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

工作sandbox here

【问题讨论】:

    标签: reactjs redux react-redux redux-saga


    【解决方案1】:

    我是 Redux 维护者。

    React-Redux 不保证您的 UI 代码将针对每个调度的操作运行。它只保证它将使用商店中的 latest 值运行。

    这是由于 React-Redux 如何管理对 store 的订阅和传播更新,以及 React 如何批量重新渲染。

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 1970-01-01
      • 2019-12-03
      • 2017-08-31
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      相关资源
      最近更新 更多