Fix Next.js 13 error: Missing react-redux context; please wrap component within <Provider>
P粉269847997
2023-08-16 15:42:17
<p>I want to use data from redux but can't solve this error. So, I have an application router in next.js 13 and I want to access my page on /settings/account. This is my file structure: </p>
<pre class="brush:php;toolbar:false;">--app
--settings
layout.jsx
page.jsx
--account
page.jsx
layout.jsx</pre>
<p>I want to access user data on the account page:</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>But I got the error:<em>Error: could not find react-redux context value; please ensure the component is wrapped in a Provider</em>. I thought using a layout to wrap the page would solve the problem, so I did this: </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}>
{children}
</Provider>
)
}</pre>
<p>Unfortunately, this doesn't help. The layout of the settings/account page and the settings page are the same, just with a different name - SettingsLayout (I thought the root layout would solve this problem). As for the settings page, it just contains plain HTML, no code.
How can I solve this problem without wrapping the <code>App</code> component? </p>
This is a tested method;
Add a new file named redux-provider.js under your application folder
Add another file named provider.tsx under your application folder and implement ReduxProvider
Implement Providers
in your layout.tsx file (a direct subcomponent of the application folder)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