我正在使用下一个react-redux软件包。如何设置初始状态?该文档仅声明withRedux函数仅接受makeStore函数作为参数。在makeStore函数中设置初始状态的默认值无效。
import {createStore} from "redux";
import rootReducer from './reducers';
/**
* @param {object} initialState
* @param {boolean} options.isServer indicates whether it is a server side or client side
* @param {Request} options.req NodeJS Request object (not set when client applies initialState from server)
* @param {Request} options.res NodeJS Request object (not set when client applies initialState from server)
* @param {boolean} options.debug User-defined debug mode param
* @param {string} options.storeKey This key will be used to preserve store in global namespace for safe HMR
*/
const makeStore = (initialState={hello: "world"}, options) => {
return createStore(rootReducer, initialState);
};
export default makeStore;
import { combineReducers } from 'redux';
import sessionReducer from './session';
import userReducer from './user';
const rootReducer = combineReducers({
sessionState: sessionReducer,
userState: userReducer,
});
export default rootReducer;
答案 0 :(得分:2)
我建议在您的单个减速器中而不是在createStore
函数中设置初始状态。尝试在各个化简器中设置初始状态,如下所示:
// auth reducer
import * as actionTypes from '../actions/actionTypes';
// INITIAL STATE!
const initState = {
authError: null,
};
// PASS INITIAL STATE INTO YOUR REDUCER!
const authReducer = (state = initState, action) => {
switch(action.type) {
// example actionType
case actionTypes.LOGIN_SUCCESS: return {...state, authError: null };
case actionTypes.LOGIN_ERROR: return {...state, authError: 'oops, error!' };
default: return state;
}
export default authReducer;
我假设您的rootReducer
只是在组合其他减速器,如下所示:
// example root reducer
import authReducer from './authReducer';
import projectReducer from './projectReducer';
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
auth: authReducer,
project: projectReducer,
});
export default rootReducer;