我正在重构一个 React/Next 应用程序,我们正在尝试实现 Redux(使用 Redux Toolkit)。我们也在从类组件切换.js到.tsx功能组件并将其重构为功能组件。现在,有多个页面执行不同数量的 API 调用以获取componentDidMount函数内的本地状态。我的想法是将它们移动到单独的位置/组件,这将在全球范围内处理它。
它们或多或少相同,加载相同的数据并遵守 DRY 原则,将它们放在每个页面组件中是没有意义的。如果某些页面确实有特定的提取,它可以自己完成,但我宁愿从一个地方/组件初始化全局状态。
在 Angular 中,我会为此使用“APP_INITIALIZER”并在应用程序之前加载状态。有没有办法在 React 中做这样的事情?是_app.tsx这样做的好地方还是我应该创建一些自定义提供程序?还是我完全错过了一些东西,我应该为此使用一些nextjs或Redux Toolkit方法?
// _app.tsx
export default function App({ Component, pageProps }: AppProps) {
const fetchMyApi = useCallback(async() => {
// do the requests, update the state
});
useEffect(() => {
fetchMyAPI();
}, [fetchMyAPI]);
return (
<ReduxProvider store={store}>
<Component {...pageProps} />
</ReduxProvider>
);
}
还是我应该创建一些可以处理它的自定义提供程序?
// _app.tsx
export default function App({ Component, pageProps }: AppProps) {
return (
<ReduxProvider store={store}>
<ReduxInitializer>
<Component {...pageProps} />
</ReduxInitializer>
</ReduxProvider>
);
}
4 年前我使用过 React/Redux,它改变了很多,我真的很困惑什么是正确的方法。