[英]error - TypeError: Cannot read properties of undefined (reading 'getState') while using redux store in next.js
Just came across this issue error - TypeError: Cannot read properties of undefined (reading 'getState')
with next.js and redux.刚刚遇到这个问题error - TypeError: Cannot read properties of undefined (reading 'getState')
。
Here is my code below, I don't know the reason why I am facing this issue.下面是我的代码,我不知道我遇到这个问题的原因。
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;
I never had dispatched any action yet, maybe dispatch later我还没有发送任何动作,也许稍后发送
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;
and finally in pages/index.js
最后在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>
)
}
Note: For more info let me tell you that I have tried the exact code in react app
also, but the same code is working in react but not working in next.js注意:有关更多信息,让我告诉你,我也在 React react app
中尝试了确切的代码,但相同的代码在 React 中有效但在 next.js 中无效
You can check the output of react
in this image您可以在此图像中检查react
的 output
You need to wrap props.你需要包裹道具。
Please see this https://github.com/kirill-konshin/next-redux-wrapper/blob/master/packages/demo-redux-toolkit/pages/_app.tsx请看这个https://github.com/kirill-konshin/next-redux-wrapper/blob/master/packages/demo-redux-toolkit/pages/_app.tsx
Export wrapper from your store.js
从您的store.js
导出包装器
import { createWrapper } from 'next-redux-wrapper';
...
export const wrapper = createWrapper(makeStore);
And your _app.js should be你的 _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.