使用 nextJS 在路由更改时自行重置 Redux 存储

Ale*_*uil 8 reactjs redux react-redux next.js

你好,我遇到了 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);
Run Code Online (Sandbox Code Playgroud)

并将组件或页面连接到我的商店,这是我的做法:

export default connect(state=>state)(Register)
Run Code Online (Sandbox Code Playgroud)

小智 -2

做这件事有很多种方法;

1将用户信息写入localStorage。重新加载浏览时,我将数据加载回useEfect中的redux

2使用下一个/链接

  • 使用 Next/Link 并不能解决这个问题。 (2认同)