嵌套的Redux Reducer返回null home状态

时间:2018-04-27 05:43:02

标签: reactjs redux reselect

我为todos嵌套了reducer。我正在使用" reselect"嵌套对象的库。下面你可以找到ADD_TODO减速器和选择器,但是当我调用ADD_TODO减速器时;它使这样的状态;

{
  0: null,
  1: null,
}

添加Todo Reducer

import { makeSelectTodos } from 'containers/HomePage/selectors';

const initialState = fromJS({
  todos: [],
  visibilityFilter: 'SHOW_ALL',
});

const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false,
      };
    default:
      return state;
  }
};

function homeReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return [
        makeSelectTodos(),
        todo(undefined, action),
      ];
    default:
      return state;
  }
}

Selector.js

import { createSelector } from 'reselect';

const selectHome = (state) => state.get('home');

const makeSelectTodos = () => createSelector(
  selectHome,
  (homeState) => homeState.get('todos')
);

export {
  selectHome,
  makeSelectTodos,
};

2 个答案:

答案 0 :(得分:0)

看起来你想要返回homeReducer中的所有待办事项,其动作类型为“ADD_TODO'”。这不太对劲。带有待办事项列表的组件必须考虑这一点,它可以通过selectAllTodos选择器获得所有待办事项。

您也没有为set_image功能提供状态。我可以看到你的选择器返回函数,它返回createSelector函数。有错误。你需要写这样的东西:

makeSelectTodos

在行动中,创作者选择器可以这样使用:

const selectHome = state => state.get('home');
const selectAllTodos = createSelector(
    selectHome,
    homeState => homeState.get('todos')
);

尽可能简化您的减速器逻辑:

// action creators:

const addTodoAction = todo => ({
    type: 'ADD_TODO',
    payload: todo
});

const addTodo = todo => (dispatch, getState) => {
    // here you able to use your selectors like:
    // const todos = selectAllTodos(getState());

    return dispatch(addTodoAction(todo));
};
祝你好运! :)

答案 1 :(得分:0)

问题在于mapStateToProps,因为没有使用不可变因此我获得了不同的数据结构。使用不可变的" getIn"我找到了解决方案。