更新组件中从减速器获取的道具

时间:2019-01-03 12:40:54

标签: reactjs redux

我在reducer中获取新数据,并通过props访问组件中的状态,但是当reducer中的状态更新时props不会更新。我需要以某种方式检查道具何时更新,componentDidMount

我试图通过this.props.list访问组件中的状态。在reducer中,当通过websocket将新项目添加到列表中时,状态为update

// Reducer
case types.ADD_LIST:
return {
  lists: action.lists
}

// Somewhere in My component
{this.props.lists ? this.props.lists.map((list, index) => (
   <li key={index}>list</li>
)}

2 个答案:

答案 0 :(得分:0)

状态不会自动映射到组件的道具。您应该使用react-redux将Redux状态映射到道具。专门在组件中使用connect方法。

示例:

const mapStateToProps = state => {
  return {
    lists: state.lists
  };
};

export default connect(mapStateToProps)(ComponentName);

别忘了将您的应用程序组件包装在提供程序中并将商店传递给它:

  <Provider store={createStore(reducers)}>
    <App />
  </Provider>

您可以查看文档here

答案 1 :(得分:0)

如果使用连接功能,则必须将状态传递给组件。 尝试这样,

const mapStateToProps = function(state) {
  return {
    lists: state.lists
  }
}

export default connect(mapStateToProps)(yourComponent);
相关问题