P粉5150665182023-08-17 11:47:45
This is a tested method;
Add a new file named redux-provider.js under your application folder
"use client"; import { PropsWithChildren } from "react"; import { Provider } from "react-redux"; import { store } from "../store/store"; // 请调整路径 export default function ReduxProvider({ children }: PropsWithChildren<any>) { return ( <Provider store={store}> {children} </Provider> ); }
Add another file named provider.tsx under your application folder and implement ReduxProvider
"use client"; import { PropsWithChildren } from "react"; import ReduxProvider from "./redux-provider"; export default function Providers({ children }: PropsWithChildren<any>) { return ( <ReduxProvider> {children} </ReduxProvider> ); }
Implement Providers
in your layout.tsx file (a direct subcomponent of the application folder)import React from "react"; import Providers from './provider'; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body> <Providers> {children} </Providers> </body> </html> ); }
Now we can access the store from other pages.
renew
Yes. but! Wrapping the root component in a ReduxProvider does not mean that all other components are client components. You can still have server components. How to do it?
Add a new folder named experimental under your application folder, and then add a new file named page.tsx under the experimental folder. You can import the contents of the page.tsx file from another file.
/experimental/page.tsx
import HomePage from "../index"; // 这是一个在其中使用redux的客户端组件 export default async function Page() { // 这是一个服务器组件 return <HomePage />; }