在CatsPage.js
的mapStateToProps
功能,輸出爲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);
作爲初始狀態而不是'{cats:[]}',你是否嘗試過只使用一個數組:'const initialState = []'和reducer' state = initialState'? – Li357
@AndrewLi很好,工作!這是做到這一點的正確方法嗎?正如你可能會說,我是一個新手去反應,減少... – AnApprentice
沒關係:)。是的,使用數組是正確的方法。根據傳遞給combineReducers的第一個參數的鍵,「combineReducers」形狀狀態是。對象'initialState'基本上是創建一個額外的對象,嵌套不好的數組。 – Li357