【问题标题】:error - TypeError: Cannot read properties of undefined (reading 'getState') while using redux store in next.js错误 - 类型错误:在 next.js 中使用 redux 存储时无法读取未定义的属性(读取 \'getState\')
【发布时间】:2022-12-10 16:56:26
【问题描述】:

刚刚遇到这个问题 error - TypeError: Cannot read properties of undefined (reading 'getState') next.js 和 redux。

下面是我的代码,我不知道我遇到这个问题的原因。

pages/app/store.js

import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "../slices/counterSlice";

export const store = configureStore({
    reducer: {
        counter : counterSlice
    }
});

pages/slices/counterSlicer.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
    count : 0
};

export const counterSlice = createSlice({
    name : "counter",
    initialState,
    reducers: {
        increment : (state , action) => {
            state.count += 1;
        }
    }
});

export const { increment } = counterSlice.actions;

export const getCount = (state) => state.counter.count;

export default counterSlice.reducer;

我还没有发送任何动作,也许稍后发送

pages/_app.js

import '../styles/globals.css'
import { Provider } from 'react-redux';
import { store } from '@reduxjs/toolkit';

function MyApp({ Component, pageProps }) {
  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  )
}

export default MyApp;

最后在pages/index.js

import styles from '../styles/Home.module.css'
import { useSelector } from 'react-redux'
import { getCount } from './slices/counterSlice'

export default function Home() {
  const value = useSelector(getCount);
  return (
    <div className={styles.container}>
      The value is {value}
     </div>
  )
}

注意:有关更多信息,让我告诉你,我也尝试过 react app 中的确切代码,但相同的代码在 React 中有效但在 next.js 中无效

您可以在此图像中检查 react 的输出

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    你需要包裹道具。

    请看这个https://github.com/kirill-konshin/next-redux-wrapper/blob/master/packages/demo-redux-toolkit/pages/_app.tsx

    从你的store.js导出包装器

    import { createWrapper } from 'next-redux-wrapper';
    ...
    export const wrapper = createWrapper(makeStore);
    

    你的 _app.js 应该是

    import '../styles/globals.css'
    import { Provider } from 'react-redux';
    import { wrapper } from './store';
    
    function MyApp({ Component, ...rest }) {
      const { store, props } = wrapper.useWrappedStore(rest);
        return (
            <Provider store={store}>
                <Component {...props} />
            </Provider>
        );
    }
    
    export default MyApp;

    【讨论】:

      猜你喜欢
      • 2022-10-05
      • 2019-06-04
      • 2023-01-20
      • 2020-01-15
      • 2021-11-05
      • 2021-05-23
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      相关资源
      最近更新 更多