首頁  >  問答  >  主體

解決 Next.js 13 錯誤:缺少 react-redux 上下文;請將元件包裹在 <Provider> 內

<p>我想使用redux中的數據,但無法解決這個錯誤。所以,我在next.js 13中有一個應用程式路由器,我想在/settings/account上訪問我的頁面。這是我的文件結構:</p> <pre class="brush:php;toolbar:false;">--app --settings layout.jsx page.jsx --account page.jsx layout.jsx</pre> <p>我想在帳號頁面存取使用者資料:</p> <pre class="brush:php;toolbar:false;">import React from 'react' import { useSelector } from 'react-redux'; export default function AccountPage() { const {info: userInfo} = useSelector(state => state.user); const {name, id} = userInfo; console.log(name, id) return ( <div>page</div> ) }</pre> <p>但是我得到了錯誤:<em>Error: could not find react-redux context value; please ensure the component is wrapped in a Provider</em>。我以為使用佈局來包裝頁面會解決這個問題,所以我做了這個:</p> <pre class="brush:php;toolbar:false;">layout.jsx "use client" import { store } from "@/context/store"; import { Provider } from "react-redux"; export default function AccountLayout({ children }) { return ( <Provider store={store}> {孩子} </Provider> ) }</pre> <p>不幸的是,這沒有幫助。 settings/account頁面和settings頁面的佈局是相同的,只是名稱不同 - SettingsLayout(我以為根佈局會解決這個問題)。至於settings頁面,它只包含普通的HTML,沒有程式碼。 如何在不包裝<code>App</code>組件的情況下解決這個問題? </p>
P粉269847997P粉269847997402 天前419

全部回覆(1)我來回復

  • P粉515066518

    P粉5150665182023-08-17 11:47:45

    這是經過測試的方法;

    在你的應用程式資料夾下新增一個名為redux-provider.js的新檔案

    "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>
        );
    }

    在你的應用程式資料夾下新增另一個名為provider.tsx的文件,並實作ReduxProvider

    "use client";
    
    import { PropsWithChildren } from "react";
    
    import ReduxProvider from "./redux-provider";
    
    export default function Providers({ children }: PropsWithChildren<any>) {
        return (
            <ReduxProvider>
                {children}
            </ReduxProvider>
        );
    }

    在你的layout.tsx檔案(應用資料夾的直接子元件)中實作Providers

    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>
        );
    }

    現在我們可以從其他頁面造訪store。

    更新

    是的。但是!將根元件包裝在ReduxProvider中並不意味著所有其他元件都是客戶端元件。你仍然可以有伺服器元件。如何做到?

    在你的應用程式資料夾下方新增一個名為experimental的新資料夾,然後在experimental資料夾下新增一個名為page.tsx的新檔案。你可以從另一個檔案匯入page.tsx檔案的內容。

    /experimental/page.tsx

    ####
    import HomePage from "../index"; // 这是一个在其中使用redux的客户端组件
    
    export default async function Page() { // 这是一个服务器组件
        return <HomePage />;
    }

    回覆
    0
  • 取消回覆