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

标签 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);

并将组件或页面连接到我的商店,这是我的做法:
export default connect(state=>state)(Register)

最佳答案

做这件事有很多种方法;
1 将用户信息写入localStorage。reload浏览时,我在useEfect中将数据加载回redux
2 使用 next/link

关于reactjs - 使用 nextJS 在路由更改时自行重置 Redux 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60393213/

相关文章:

reactjs - "Uncaught TypeError: Cannot read property ' 类型 ' of undefined"并不清楚它与什么相关

javascript - 如何将 dispatch 传递到 prop 之类的组件中?

javascript - 在 React 组件中使用谷歌地图

javascript - Redux-logger 导出已更改

javascript - React-Redux 组件不反射(reflect) Redux Store 中的变化

redux - 在调度 Redux Action 之前检查 AppState?

redux - 第一次完成后如何调用 RTK 突变

javascript - 在 React JS 的文本字段中打印 JSON 数据

reactjs - this.handleChange = this.handleChange.bind(this);

javascript - 如何在不将文本包装在 span 中的情况下在 ReactJS 中输出文本