您好,我遇到了 Redux 和 NextJS 的问题,当我使用 API 登录我的应用程序时,我的用户信息完美地存储在 redux 存储中,感谢 reduxApiMiddleware,
但是当我重新加载浏览器或更改路线时,我的商店会恢复到初始状态:/。
我真的没有找到解决这个问题的方法,我尝试使用 redux-persist 但没有任何效果
这是我的 _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)
最佳答案
做这件事有很多种方法;
1 将用户信息写入localStorage。reload浏览时,我在useEfect中将数据加载回redux
2 使用 next/link
关于reactjs - 使用 nextJS 在路由更改时自行重置 Redux 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60393213/