热重载时Create-React-App失去Redux存储状态

时间:2019-01-04 18:52:46

标签: javascript reactjs redux create-react-app hot-module-replacement

我已经使用Create-React-App创建了一个应用程序,并且热重装工作正常,但是Redux状态丢失了。如果我编辑任何组件,例如要更改标题,状态会丢失-最令人讨厌的是,由于状态中存储的令牌丢失,用户已注销。我遵循了包括(https://redux.js.org/recipes/configuring-your-store)在内的各种示例,并且无法弄清这里出了什么问题。

有什么想法我错过了吗?谢谢!

index.js

const renderApp = () => {
    ReactDOM.render(
        <App />, document.getElementById('root')
    );
};

if (process.env.NODE_ENV !== 'production' && module.hot) {
    module.hot.accept('./App', renderApp);
}

renderApp();

store.js

const inititalState = {};

const store = createStore(
    rootReducer, 
    inititalState, 
    compose(applyMiddleware(thunk), 
        window.__REDUX_DEVTOOLS_EXTENSION__&& window.__REDUX_DEVTOOLS_EXTENSION__()));

if (process.env.NODE_ENV !== 'production' && module.hot) {
    module.hot.accept('./reducers', () => store.replaceReducer(rootReducer));
}

export default store;

reducers / index.js

import { combineReducers } from 'redux';
import errorReducer from './errorReducer';
import authReducer from './authReducer';

export default combineReducers({
    'errors': errorReducer,
    'auth': authReducer,
});

App.js:

class App extends Component {
    render() {
        return (
            <Provider store = { store }>
                <Router>
                    <div>
                        <Navbar />
                        <Route exact path="/" component={ Home } />
                        <div className="container">
                            <Route exact path="/register" component={ Register } />
                            <Route exact path="/login" component={ Login } />
                            <Route exact path="/forgotpassword" component={ ForgotPassword } />
                        </div>
                    </div>
                </Router>
            </Provider>
        );
    }
}

export default App;

来自package.json:

  "dependencies": {
    "bootstrap": "^4.2.1",
    "classnames": "^2.2.6",
    "jquery": "^3.3.1",
    "jwt-decode": "^2.2.0",
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-redux": "^6.0.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.2",
    "reactstrap": "^7.0.2",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    "updeep": "^1.1.0"
  },

2 个答案:

答案 0 :(得分:1)

如果只需要保存令牌,则可以使用localstorage,如果要保存大量数据,则应查看redux-persist。

使用localStorage保存的示例:

localStorage.setItem(token, res.data.token);

使用localStorage进行检索的示例:

localStorage.getItem(token);

用户注销后删除令牌的示例:

localStorage.removeItem(token);

答案 1 :(得分:0)

看看redux-persist库,它会保存您的redux状态,然后对其进行补水。