Redux:通过同步调度更新商店

时间:2017-01-20 05:41:06

标签: reactjs redux react-redux

我正在尝试通过在componentWillMount()上调度更新商店的操作来渲染2个组件的简单示例。

初始状态:

export default {
  dashboards: [],
  dashboardContent: []
};

2减速器:

export default function dashboardContentReducer(state = initialState.dashboardContent, action) {
  switch(action.type) {
    case types.LOAD_DASHBOARD_CONTENT_SUCCESS:
      return action.dashboardContent;
    default:
      return state;
  }
}

export default function dashboardReducer(state = initialState.dashboards, action) {
  switch(action.type) {
    case types.LOAD_DASHBOARDS_SUCCESS:
      return action.dashboards;
    default:
      return state;
  }
}

这里的事情变得有些奇怪。

我能够调度动作来调用这些reducers,但只有其中一个将用于更新redux store。我按如下方式这样做:

class NavigationBar extends React.Component {

  constructor(props) {
    super(props);
  }

  componentWillMount() {
    this.props.dispatch(dashboardActions.loadDashboards());
  }

  render() {
    return (
      <div className="rc-navigationBar">
        <h1>Navigation!</h1>
          {this.props.dashboards.map((dashboard, index) => {
            return <h1 key={index}>{dashboard.title}</h1>
          })}
      </div>
    );
  }
}

和另一个:

class ContentPage extends React.Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
  this.props.dispatch(dashboardContentActions.loadDashboardContent(extractIdFromRoute()));
  }

  render() {
    return (
      <div>
        <h1>Content!</h1>
          {this.props.dashboardContent.map((content, index) => {
            return <h1 key={index}>{content.application}</h1>;
          })}
      </div>
    );
  }
}

当我同时尝试修改商店时,我收到此错误:

Uncaught (in promise) Error: A state mutation was detected between dispatches, in the path 'dashboards.1.filter.Pivot.ancestorOrigins'. This may cause incorrect behavior.

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

你以错误的方式归还它。它应该是这样的 -

export default function dashboardContentReducer(state = default, action) {
  switch(action.type) {
    case types.LOAD_DASHBOARD_CONTENT_SUCCESS:
                return Object.assign({}, state, { dashboardContent:action.dashboardContent });
    default:
      return state;
  }
}