我的Redux mapStateToProps函数遇到麻烦,抛出一个错误,指出state.currentOpportunities未定义。奇怪的是,当我在console.log中进行控制台操作时,只能在state._root.entries 1。organization.currentOpportunity下访问,而不是在state.organization.currentOpportunity下访问达到了organizationReducer中定义的初始状态。主index.js文件中的.log状态
App.js主文件
const initialState = {}
const history = createHistory();
const store = configureStore(initialState, history);
const MOUNT_NODE = document.getElementById('app');
const render = messages => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</LanguageProvider>
</Provider>,
MOUNT_NODE,
);
};
organizationReducer.js
const initialState = {
currentOpportunities: [],
expiredOpportunities: []
};
export default function (state=initialState, action) {
switch(action.type) {
case FETCH_ORGANIZATION_OPPORTUNITIES:
return {...state, data: action.payload}
case FETCH_CURRENT_OPPORTUNITIES:
return{...state, currentOpportunities: action.payload}
case FETCH_EXPIRED_OPPORTUNITIES:
return{...state, expiredOpportunities: action.payload}
default:
return state
}
}
我的root reducer文件
export default function createReducer(injectedReducers) {
return combineReducers({
organization: organizationReducer,
...injectedReducers
})
}
index.js文件
const mapStatetoProps = (state) => {
console.log(state)
return {
currentOpportunities: state.organization.currentOpportunities,
expiredOpportunities: state.organization.expiredOpportunities
};
}
export default connect(mapStatetoProps, actions)(OpportunitiesPage);
有人知道这里会发生什么吗?
答案 0 :(得分:-1)
state.organization.currentOpportunity
未定义,因为状态是一个不变的映射,并且您尝试像访问对象一样访问其字段。 1
您必须更新reducer逻辑以使用不可变的API,在其中合并对象例如
case FETCH_ORGANIZATION_OPPORTUNITIES:
return state.merge({data: action.payload})
或从不可变数据结构转换为可变的javascript对象。例如
stateObject = state.toJS()
return {
currentOpportunities: stateObject.organization.currentOpportunities,
//...
由于它可能会导致跟踪某个对象实例处于什么状态的麻烦,因此建议您在组件状态下坚持使用不可变数据结构或可变Javascript对象。
这里是使用不可变地图API的mapStateToProps。 2
return {
currentOpportunities: state.getIn(['organization', 'currentOpportunities'])
//...