问题
I'm currently using redux-persist to persistent data storage in my react-redux application. I have set it up according to the documentation. I have tested it on a separate project with npx create-react-app
. The persistent storage was working properly.
When I integrate it in my actual working project, the state saving doesn't work. Can someone help me with this?
Here is my store.js:
import { createStore, applyMiddleware, compose } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import rootReducers from './reducers';
// imports for persistance redux state
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
const middleware = [thunk, routerMiddleware(history)];
const initialState = {};
//config for redux-persist
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, rootReducers)
function composeWithApplyMiddlewares() {
if (window.__REDUX_DEVTOOLS_EXTENSION__) {
return compose(applyMiddleware(...middleware), window.__REDUX_DEVTOOLS_EXTENSION__());
}
return compose(applyMiddleware(...middleware));
}
const createMyStore = () =>
createStore(
persistedReducer,
initialState,
composeWithApplyMiddlewares(),
);
let persistor = persistStore(createMyStore());
export default createMyStore();
index.js:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { Router, Route, browserHistory } from 'react-router';
import RandomID from 'random-id';
import 'normalize.css/normalize.css';
import 'plottable/plottable.css';
import store from './store';
import SignInContainer from './containers/Auth/Signin';
import SignUpContainer from './containers/Auth/Signup';
import ForgotPasswordContainer from './containers/Auth/ForgotPassword';
import ResetPasswordContainer from './containers/Auth/ResetPassword';
import CompleteSignupContainer from './containers/Auth/CompleteSignup';
import UsersListContainer from './containers/Users/List';
import CreateEndpointContainer from './containers/Endpoints/CreateEndpoint';
import TestMessagesContainer from './containers/TestMessages';
import Dashboard from './containers/Dashboard';
import initialize from './actions/initialize';
import Setting from './containers/Setting/Main';
const root = document.getElementById('root');
const history = syncHistoryWithStore(browserHistory, store);
const rand = RandomID(16, 'A0');
localStorage.setItem('authStateKey', rand);
const reduxOauthConfig = {
backend: {
apiUrl: 'http://0.0.0.0:4000', // TODO: Change backend URL here
signOutPath: null, // Add signout path to destroy session token
tokenValidationPath: '/svr/ping',
authProviderPaths: {
facebook: '/svr/auth/facebook',
github: '/svr/auth/github',
gitlab: '/svr/auth/gitlab',
google: '/svr/auth/google',
twitter: '/svr/auth/twitter',
},
},
};
const requireAuth = (nextState, replace) => {
const state = store.getState();
const isSignedIn = state.auth.authUser.isSignedIn;
// const isSignupCompleted = state.auth.authUser.isSignupCompleted;
// Complete signup first before user can do anything
// if (!isSignupCompleted && nextState.location.pathname !== '/complete-signup') {
// replace({
// pathname: '/complete-signup',
// state: { nextPathname: nextState.location.pathname },
// });
// }
if (!isSignedIn) {
replace({
pathname: '/signin',
state: { nextPathname: nextState.location.pathname },
});
}
};
const publicOnly = (nextState, replace) => {
const state = store.getState();
const isSignedIn = state.auth.authUser.isSignedIn;
if (isSignedIn) {
replace({
pathname: '/',
state: { nextPathname: nextState.location.pathname },
});
}
};
store.dispatch(initialize(reduxOauthConfig)).then(
() => {
render(
<Provider store={store}>
<Router history={history}>
<Route exact path="/signup" component={SignUpContainer} onEnter={publicOnly} />
<Route exact path="/signin" component={SignInContainer} onEnter={publicOnly} />
<Route exact path="/forgot-password" component={ForgotPasswordContainer} onEnter={publicOnly} />
<Route exact path="/reset-password" component={ResetPasswordContainer} onEnter={publicOnly} />
<Route exact path="/complete-signup" component={CompleteSignupContainer} onEnter={requireAuth} />
<Route exact path="/users" component={UsersListContainer} onEnter={requireAuth} />
<Route exact path="/chat" component={TestMessagesContainer} onEnter={requireAuth} />
<Route exact path="/add-endpoint" component={CreateEndpointContainer} onEnter={requireAuth} />
<Route exact path="/" component={Dashboard} onEnter={requireAuth} />
<Route exact path="/:userId/setting" component={Setting} onEnter={publicOnly} />
</Router>
</Provider>
, root,
);
},
);
reducers/index.js:
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import message from './message';
import users from './users';
import endpoints from './endpoints';
import toasts from './toasts';
import auth from './auth';
export default combineReducers({
routing: routerReducer,
users,
endpoints,
ui: toasts,
chat: message,
auth,
});
Thanks for your attention.
来源:https://stackoverflow.com/questions/51319244/unable-to-save-redux-state-with-redux-persist