你好,我有一个问题与Redux和NextJS,当我登录我的应用程序与API,我的用户的信息是完全存储在redux商店,感谢reduxApiMiddleware,但当我重新加载我的浏览器或改变路由我的商店回到它的初始状态:/。
我并没有找到解决这个问题的方法,我尝试使用redux-persistent,但没有任何效果
下面是我的_app.js文件:
// pages/_app.jsx
import React from "react";
import {createStore,applyMiddleware} from "redux";
import {Provider} from "react-redux";
import App,{Container} from "next/app";
import withRedux from "next-redux-wrapper";
import reducer from '../redux/reducers/index'
import { apiMiddleware } from "redux-api-middleware";
import { PersistGate } from 'redux-persist/integration/react';
/**
* @param {object} initialState The store's initial state (on the client side, the state of the server-side store is passed here)
* @param {boolean} options.isServer Indicates whether makeStore is executed on the server or the client side
* @param {Request} options.req Node.js `Request` object (only set before `getInitialProps` on the server side)
* @param {Response} options.res Node.js `Response` object (only set before `getInitialProps` on the server side)
* @param {boolean} options.debug User-defined debug flag
* @param {string} options.storeKey The key that will be used to persist the store in the browser's `window` object for safe HMR
*/
const createStoreWithMiddleware = applyMiddleware(apiMiddleware)(createStore);
export function configureStore(initialState,options) {
return createStoreWithMiddleware(reducer, initialState);
}
class MyApp extends App {
static async getInitialProps({Component, ctx}) {
// We can dispatch from here too
// ctx.store.dispatch({type: 'FOO', payload: 'TOTO'});
const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};
return {pageProps};
}
render() {
const {Component, pageProps, store} = this.props;
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
}
export default withRedux(configureStore)(MyApp);
要将组件或页面连接到我的商店,我是这样做的:
export default connect(state=>state)(Register)
2条答案
按热度按时间tp5buhyn1#
我看到你还没有实现
redux-persist/integration/react
的PersistGate
组件,或者至少在代码示例中缺少它,这个组件是需要持久化redux状态的。有关持久化配置的更多信息,请查看redux-persists在其Github存储库中的文档。
eqoofvh92#
有几种方法可以做到这一点;
1将用户信息写入localStorage,reload browse时,我在useEffect中将数据加载回redux
2使用**next/link**