为什么我的Redux状态不正确?

时间:2017-05-25 04:49:17

标签: reactjs redux react-redux

CatsPage.js的{​​{1}}函数中,mapStateToProps的输出显示:

console.log(state)

当我想要的嵌套是:

Object
    Cats (Object)
        Cats (Array)

我做错了什么?

setup.js

Object
    Cats (Array)

catReducer.js

import cats from '../reducers/catReducer';

let store;

const initStore = ({onRehydrationComplete}) => {

  store = createStore(
    combineReducers({
      ...reactDeviseReducers,
      form: formReducer,
      router: routerReducer,
      apollo: apolloClient.reducer(),
      cats
    }),
    {},
    compose(
      applyMiddleware(
        thunk,
        routerMiddleware(history),
        apolloClient.middleware()
      ),
      autoRehydrate(),
      window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
  );

  persistStore(store, {
    blacklist: [
      'form'
    ]
  }, onRehydrationComplete);

  return store;
};

CatsPage.js

import * as types from '../actions/actionTypes';

const initialState = {
  cats: []
}

export default function catReducer(state = initialState.cats, action) {
  return state
}

2 个答案:

答案 0 :(得分:2)

构建初始状态的方式导致您看到的不需要的嵌套。不要使用对象作为初始状态,只需使用数组来摆脱嵌套:

const initialState = [];

并设置reducer的初始状态:

function catReducer(state = initialState, action) {
    ...
}

由于catReducer仅控制状态切片,因此它仅控制猫的数组。因此,它的初始状态片应该只是数组,而不是持有数组的对象;这破坏了理想的结构。

答案 1 :(得分:0)

  

我做错了什么?

以下代码段错误

export default function catReducer(state = initialState.cats, action) {
  return state
}

state = initialState.cats正在将state设置为数组。如果您希望它成为对象,您应该state = initialState