我正在尝试更改 redux 中 const 的状态。 我正在尝试直接在要更改状态的组件中进行分派(dispatch)。分派(dispatch)后状态已更改,但是我取回了一个对象。当我使用 Console.log 时,我得到 [Object][Object] ,在调用 dispatch 之前我用来获取状态的值。
这是我的商店。
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;
这是我的主 Reducer。
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);
我成功地从商店检索了状态,但是当我发送时,我取回了一个对象。
sidebarReducer.js:13 reducer called
sidebarReducer.js:14 wrapper slide-menu
App.js:38 sidebarname is [object Object]
App.js:40 wrapper slide-menu
最佳答案
在处理您的操作时,您将返回一个对象(检查大括号):
return {
...state,
sidebarname: action.payload
};
因为你的整个状态只是字符串sidebarname
,你应该只返回有效载荷:
return action.payload
或者,你可以让你的状态成为一个对象,然后你的 Action 返回应该就可以正常工作了:
let initialState = { sidebarmenu: "wrapper slide-menu" };
...
export default function(state=initialState,action){
...
}
关于javascript - Redux Reducer 正在返回一个 [Object Object] ,但是我想要字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51319526/