2017-05-25 35 views
0

CatsPage.jsmapStateToProps功能,輸出爲console.log(state)顯示的是:爲什麼我的Redux狀態不正確?

Object 
    Cats (Object) 
     Cats (Array) 

當我想要嵌套是:

Object 
    Cats (Array) 

我在做什麼錯?

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

catReducer.js

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

const initialState = { 
    cats: [] 
} 

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

CatsPage.js

import React from 'react'; 
import PropTypes from 'prop-types'; 
import {connect} from 'react-redux'; 
import CatList from './CatList'; 
import {loadCats} from '../../actions/catActions'; 

class CatsPage extends React.Component { 
    componentDidMount() { 
    console.log('CatsPage: componentDidMount'); 
    this.props.dispatch(loadCats()) 
    } 
    render() { 
    return (
     <div> 
     <h1>Cats</h1> 
     <div> 
      <CatList cats={this.props.cats} /> 
     </div> 
     </div> 
    ); 
    } 
} 

CatsPage.propTypes = { 
    cats: PropTypes.array.isRequired 
}; 

function mapStateToProps(state, ownProps) { 

    console.log('mapStateToProps') 
    console.log(state) 

    return { 
    cats: state.cats 
    //cats: [{id:1, name: "Maru"}] 
    }; 
} 

export default connect(mapStateToProps)(CatsPage); 
+1

作爲初始狀態而不是'{cats:[]}',你是否嘗試過只使用一個數組:'const initialState = []'和reducer' state = initialState'? – Li357

+0

@AndrewLi很好,工作!這是做到這一點的正確方法嗎?正如你可能會說,我是一個新手去反應,減少... – AnApprentice

+1

沒關係:)。是的,使用數組是正確的方法。根據傳遞給combineReducers的第一個參數的鍵,「combineReducers」形狀狀態是。對象'initialState'基本上是創建一個額外的對象,嵌套不好的數組。 – Li357

回答

2

構建初始狀態的方式會導致您看到不想要的嵌套。而不是使用一個對象作爲初始狀態,只需使用一個數組來擺脫嵌套:

const initialState = []; 

,並設置減速機的初始狀態,像這樣:

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

由於catReducer只控制切片狀態,它只控制貓的數組。因此,它的初始狀態切片應該只是數組,而不是一個擁有數組的對象;這會破壞所需的結構。

0

我在做什麼錯?

下面的代碼段是錯誤

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

state = initialState.cats是設置state到陣列。如果你希望它是一個對象,你應該做state = initialState

+0

OP *不希望處於狀態的對象,他們想要一個數組... – Li357