【问题标题】:Redux state has changed, why doesn't it trigger a re-render? (Redux-saga)Redux 状态发生了变化,为什么不触发重新渲染? (Redux 传奇)
【发布时间】:2022-01-13 17:08:39
【问题描述】:

我正在使用 react + redux + redux saga

我在渲染页面时遇到了问题(GET 调用) 调用应该是这样的:

  1. 构造函数
  2. 渲染()
  3. componentDidMount
  4. 渲染()

但我刚刚到达componentDidMountmapDispatchToProps 正在调度操作,API 调用正在工作,通过它从服务器获取响应并将数据更新到状态。 但是它在某处丢失了,我的组件甚至没有重新渲染。 直到减速器,我正在获取要返回的数据action.items

itemReducer.js

const itemReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.GET_ALL_ITEMS_SUCCESS:
      console.log("itemReducer-----", action.items); //getting the data over here
      return action.items;
    default:
      return state;
  }
};

itemPage.js(组件)

class ItemsPage extends React.Component {
      componentDidMount() {
        this.props.loadItems();
      }

     render() {
        const { items } = this.props; // not even it renders, so not getting data
        ...
        return (<div>...</div>);
     }
}

const mapStateToProps = (state) => {
  return {
    items: state.items,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    loadItems: () => dispatch(loadAllItemsAction()),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(ItemsPage);

请给一些建议,提前致谢 :D

【问题讨论】:

    标签: reactjs redux react-redux axios redux-saga


    【解决方案1】:

    您需要了解 render/componentDidMount 的调用并不像预期的那样线性。当所有子级都mount 时,componentDidMount 会触发。这并不意味着 render() 已经完成了。

    阅读此处了解更多信息: https://github.com/facebook/react/issues/2659

    【讨论】:

      【解决方案2】:

      您发布的代码没有问题。为了确保我几乎复制粘贴了您共享的代码,填写了缺失的部分并且它工作得很好: https://codesandbox.io/s/3tuxv?file=/src/index.js

      我猜可能有问题的是您的项目没有存储在 state.items 中,而是在一些不同的路径下,或者您可能缺少 react-redux 提供程序,但是如果没有看到更多代码就不可能肯定地说.

      【讨论】:

      • 感谢 @martin-kadlec,您的 sn-p 帮助我找到了丢失的部分,即 items: itemReducer,我丢失了密钥 items
      猜你喜欢
      • 2017-01-23
      • 2020-07-26
      • 2021-06-12
      • 2019-05-07
      • 2019-02-13
      • 2018-12-31
      • 1970-01-01
      • 2021-08-06
      • 2020-03-30
      相关资源
      最近更新 更多