我试图在redux中更改const的状态 . 我正在我想要更改状态的组件中直接尝试我的调度 . 在调度后状态被更改,但是我得到了一个对象 . 当我在Console.log中,我得到[对象] [对象],在调用调度之前我曾经获得状态的值 .
这是我的商店 .
import { createStore,applyMiddleware , compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
//const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
这是我的主减速机 .
import { combineReducers } from 'redux';
import sidebarReducer from './sidebarReducer';
export default combineReducers({
name : sidebarReducer
});
这是我的CustomReducer,我称之为sidebarReducer .
import { TOGGLE_SIDEBAR } from '../actions/types';
let sidebarname = "wrapper slide-menu";
export default function(state=sidebarname,action){
switch(action.type){
case TOGGLE_SIDEBAR:
console.log('reducer called');
console.log(state);
return{
...state,
sidebarname : action.payload
};
}
return state;
}
这是我的Dispatch和MapStatetoProps函数 .
const mapStatetoProps = state => ({
name : state.name
});
const mapDispatchtoProps = dispatch => ({
setName : (name) => {
dispatch({
type: "TOGGLE_SIDEBAR",
payload: name
})
}
})
export default connect(mapStatetoProps,mapDispatchtoProps)(App);
我成功地从商店中检索了State,但是当我发送时我得到了一个Object .
sidebarReducer.js:13 reducer called
sidebarReducer.js:14 wrapper slide-menu
App.js:38 sidebarname is [object Object]
App.js:40 wrapper slide-menu
2 回答
在处理您的操作时,您将返回一个对象(检查花括号):
由于您的整个状态只是字符串
sidebarname
,因此您应该只返回有效负载:或者,您可以将您的州作为一个对象,然后您的行动返回应该正常工作:
你的sidebarReducer只管理一个字符串 . 只需在TOGGLE_SIDEBAR上返回action.payload,而不是具有
sidebarname
属性的对象 .