我已经按照预期的格式设置了 _app.js 和 store.js。这是我第一次尝试同时使用两者,所以如果我遗漏了一些明显的东西,请告诉我。
store.js:
import { configureStore } from '@reduxjs/toolkit';
import { createWrapper } from 'next-redux-wrapper';
import authReducer from '../store/slices/authSlice';
import searchReducer from '../store/slices/searchSlice';
const makeStore = () => {
console.log('config store: ', configureStore({ reducer: { auth, search } }));
return configureStore({
reducer: {
auth: authReducer,
search: searchReducer,
},
});
}
export const wrapper = createWrapper(makeStore, { debug: process.env.NODE_ENV === 'development' });
_app.js:
import { Provider } from 'react-redux';
import { wrapper } from '../store/store';
function MyApp({ Component, pageProps }) {
console.log('wrapper: ', wrapper);
return (
<Provider store={wrapper}>
<Component {...pageProps} />
</Provider>
);
}
export default MyApp;
我的包装器的console.log是:
wrapper: {
getServerSideProps: [Function: getServerSideProps],
getStaticProps: [Function: getStaticProps],
getInitialAppProps: [Function: getInitialAppProps],
getInitialPageProps: [Function: getInitialPageProps],
withRedux: [Function: withRedux],
useWrappedStore: [Function: useWrappedStore]
}
我完成这一切的原因是因为我最初在使用 withRedux 时遇到了遗留错误,所以它说我必须使用 createWrapper 选项。
我尝试在此处、ChatGPT 和 Gemini 上查找,但似乎没有任何内容可以解释为什么我收到 TypeError: store.getState is not a function。看起来 makeStore 永远不会被调用,因为函数中的 console.log 永远不会记录。
wrapper
返回您在访问商店之前需要首先使用的功能。您直接将 wrapper
作为 store
传递。
参见包装器用法。
使用
useWrappedStore
挂钩:
import { Provider } from 'react-redux';
import { wrapper } from '../store/store';
function MyApp({ Component, pageProps }) {
const { store, props } = wrapper.useWrappedStore(pageProps);
return (
<Provider store={store}>
<Component {...props} />
</Provider>
);
}
export default MyApp;
使用
withRedux
高阶组件:
import { Provider } from 'react-redux';
import { wrapper } from '../store/store';
function MyApp({ Component, pageProps }) {
return (
<Component {...props} />
);
}
export default wrapper.withRedux(MyApp);