繁体   English   中英

错误 - 类型错误:使用 next.js 中的 redux 存储时无法读取未定义的属性(读取“getState”)

[英]error - TypeError: Cannot read properties of undefined (reading 'getState') while using redux store in next.js

刚刚遇到这个问题error - TypeError: Cannot read properties of undefined (reading 'getState')

在此处输入图像描述

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

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 react app中尝试了确切的代码,但相同的代码在 React 中有效但在 next.js 中无效

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

在此处输入图像描述

你需要包裹道具。

请看这个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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM