【发布时间】:2022-01-22 08:58:49
【问题描述】:
我在 Next.js 应用程序中使用 RTK (redux-toolkit)。我正在尝试在“getInitialProps”中调度一个 AsyncThunk Action。搜索时,我发现了一个名为“next-redux-wrapper”的包,它公开了“getInitialProps”中的“store”,但我正在努力弄清楚如何让它与我的项目一起使用。
这是一个项目的准系统示例,我目前正在使用带有 2 个减速器的 Typescript。一个 reducer 使用 AsyncThunk 从 API 获取数据。我已经安装了“next-redux-wrapper”,但我不知道如何实现它,以便所有页面都可以访问“getInitialProps”中的“store”。该软件包的文档有一个示例,但比较令人困惑。
这是我的 store.ts 的样子...
import { Action, configureStore, ThunkAction } from '@reduxjs/toolkit';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';
import { counterReducer } from '../features/counter';
import { kanyeReducer } from '../features/kanye';
export const store = configureStore({
reducer: {
counter: counterReducer,
kanyeQuote: kanyeReducer,
},
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>;
如您所见,我导入了next-redux-wrapper,仅此而已。
这就是我的“_app.tsx”的样子......
import { Provider } from 'react-redux';
import type { AppProps } from 'next/app';
import { store } from '../app/store';
function MyApp({ Component, pageProps }: AppProps) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
export default MyApp;
我需要能够在此页面的“getInitialProps”中调度“getKanyeQuote”操作...
import React from 'react';
import { useAppDispatch, useAppSelector } from '../app/hooks';
import { getKanyeQuote } from '../features/kanye';
const kanye: React.FC = () => {
const dispatch = useAppDispatch();
const { data, pending, error } = useAppSelector((state) => state.kanyeQuote);
return (
<div>
<h2>Generate random Kanye West quote</h2>
{pending && <p>Loading...</p>}
{data && <p>{data.quote}</p>}
{error && <p>Oops, something went wrong</p>}
<button onClick={() => dispatch(getKanyeQuote())} disabled={pending}>
Generate Kanye Quote
</button>
</div>
);
};
export default kanye;
这里有一个完整示例的链接。 https://stackblitz.com/edit/github-bizsur-zkcmca?file=src%2Ffeatures%2Fcounter%2Freducer.ts
非常感谢任何帮助。
【问题讨论】:
标签: typescript redux next.js redux-thunk redux-toolkit