2017-01-20 98 views
-1

我正在尝试一个简单示例,通过在componentWillMount()上调度更新商店的操作来呈现2个组件。Redux:使用同步调度更新商店

初始状态:

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; 
    } 
} 

这就是事情变得有点怪异。

我能够调度行动来调用这些减速器,但只有其中一个将更新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

您正在以错误的方式返回它。它应该是这样的 -

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; 
    } 
} 
+0

这两个返回应该以这种方式完成? – iggy2012

+0

是的。每次你必须从reducer返回新的Object。这样它会保持状态的可变性。 –

+0

嗯...这似乎已经把我的数组初始状态变成了一个对象。我如何让它保持一个阵列? – iggy2012