首页 > 解决方案 > React-Redux mapStateToProps 不更新组件

问题描述

所以我简化了我的代码,但基本上我有一个直截了当的 redux 商店:

/* store.js */

import { createStore } from 'redux';

const reducer = (state = {}, action) => {
  if (action.type === 'action') state.data = data;
  return state;
}

const store = createStore(reducer);

store.subscribe(() => {
  console.log(store.getState()); // returns the right state, updates properly
});

export default store;

从服务器拉取数据并将其分派到存储的加载器:

/* Loader.js */

class Loader {
  dispatch (allDocuments) {
    store.dispatch({
      type: 'action',
      data: data
    });
  }

  async fetchData () {
    try {
      const allDocuments = await ajaxCall('GET', '/fetchData');
      this.dispatch(allDocuments);
      return allDocuments;
    } catch (e) {
      console.error(e);
    }
  }
}

export default Loader;

然后这是我的 App.js 文件,我每 5 秒触发一次 Loader fetch 方法,并将存储状态映射到 React 组件:

/* App.js */

import Loader from './Loader';
const loader = new Loader();

setInterval(async () => {
  await loader.fetchData();
}, 5000);

const App = ({
  data
}) => {
  console.log(data); //doesn't update

  return (
    <div>
      <p>{data}</p>
    </div>
  )
};

const mapStateToProps = state => ({data: state.data,})

export default connect(mapStateToProps)(App);

所以这里的问题是组件没有更新。Loader 正确调度,redux store 确实得到了更新,但 App 中的 data 属性仍然是一个空对象,并且不会重新触发 render 方法。

为什么 mapStateToProps 在 store 状态发生变化时不更新组件?

标签: reactjsreduxreact-redux

解决方案


您的减速器不会保存action.data有效负载。它也没有返回新的状态对象引用。

const reducer = (state = {}, action) => {
  if (action.type === 'action') state.data = data; // <-- mutation
  return state;
}

当动作类型匹配时,您应该返回一个带有action.data有效负载的新状态对象引用。

const reducer = (state = {}, action) => {
  if (action.type === 'action') {
    return {
      ...state,
      data: action.data;
    };
  }

  return state;
}

推荐阅读