Bip*_*pin 5 redux app-router next.js redux-toolkit
如何在 NextJS 13 应用路由器中使用 Redux 工具包?
这些是我与 redux 工具包相关的所有片段和代码,代码有什么问题吗,因为我在终端中收到此错误,说,我认为在 Nextjs 13 中,我们必须像我一样创建一个单独的提供程序,但我不知道错误请帮我找出错误:
apiSlice.js:
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
const baseQuery = fetchBaseQuery({
baseUrl: "http://localhost:8000/",
credentials: "include",
});
export const apiSlice = createApi({
baseQuery,
tagTypes: ["User"],
endpoints: (builder) => ({}),
});
Run Code Online (Sandbox Code Playgroud)
usersApiSlice.js:
import { apiSlice } from "./apiSlice";
const USERS_URL = "http://localhost:8000/api/users";
export const usersApiSlice = apiSlice.injectEndpoints({
endpoints: (builder) => ({
login: builder.mutation({
query: (data) => ({
url: `${USERS_URL}/auth`,
method: "POST",
body: data,
}),
}),
register: builder.mutation({
query: (data) => ({
url: `${USERS_URL}`,
method: "POST",
body: data,
}),
}),
logout: builder.mutation({
query: () => ({
url: `${USERS_URL}/logout`,
method: "POST",
}),
}),
}),
});
export const { useLoginMutation, useLogoutMutation, useRegisterMutation } =
usersApiSlice;
Run Code Online (Sandbox Code Playgroud)
authSlice.js :
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
userInfo: null,
};
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
setCredentials: (state, action) => {
state.userInfo = action.payload;
localStorage.setItem("userInfo", JSON.stringify(action.payload));
},
logout: (state, action) => {
state.userInfo = null;
localStorage.removeItem("userInfo");
},
},
});
export default authSlice.reducer;
export const { setCredentials, logout } = authSlice.actions;
Run Code Online (Sandbox Code Playgroud)
提供者.js:
"use client";
import { Provider } from "react-redux";
import { store } from "./store";
export function Providers({ children }) {
return <Provider store={store}>{children}</Provider>;
}
export default Providers;
Run Code Online (Sandbox Code Playgroud)
商店.js:
import { configureStore } from "@reduxjs/toolkit";
import authReducer from "./features/auth/authSlice";
import { apiSlice } from "./features/api/apiSlice";
export const store = configureStore({
reducer: {
auth: authReducer,
[apiSlice.reducerPath]: apiSlice.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
devTools: true,
});
Run Code Online (Sandbox Code Playgroud)
布局.js:
"use client";
import "./globals.css";
import { Providers } from "./GlobalRedux/provider";
// import { ToastContainer } from "react-toastify";
// import "react-toastify/dist/ReactToastify.css";
import { Inter } from "next/font/google";
import Header from "./components/Header";
import { Provider } from "react-redux";
import { store } from "./GlobalRedux/store";
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={inter.className}>
<Provider store={store}>
<Header />
{children}
</Provider>
</body>
</html>
);
}
Run Code Online (Sandbox Code Playgroud)
登录/page.jsx:
"use client";
import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLoginMutation } from "@/app/GlobalRedux/features/api/usersApiSlice";
import { setCredentials } from "@/app/GlobalRedux/features/auth/authSlice";
import { useRouter } from "next/navigation";
// import { toast } from "react-toastify";
import styles from "../loginregister.module.css";
const page = () => {
const router = useRouter();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const dispatch = useDispatch();
const [login, { isLoading, error }] = useLoginMutation();
const { userInfo } = useSelector((state) => state.auth);
useEffect(() => {
if (userInfo) {
router.push("/");
}
}, [router, userInfo]);
const submitHandler = async (e) => {
e.preventDefault();
try {
const res = await login({ email, password });
dispatch(setCredentials({ ...res }));
if (res.data.status === 201) {
router.push("/");
}
} catch (err) {
alert(err?.data?.message || err.error);
// toast.error(err?.data?.message || err.error);
}
};
return (
<div className={styles.form}>
<h1>Login</h1>
<form onSubmit={submitHandler}>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
type="email"
name="email"
placeholder="Email"
/>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
type="password"
name="password"
placeholder="Password"
/>
{isLoading && <h2>Loading...</h2>}
<button>Login</button>
</form>
</div>
);
};
export default page;
Run Code Online (Sandbox Code Playgroud)
小智 4
在 jsx 或 tsx 中创建 \xc3\xa0 ReduxProvider :
\n"use client";\nimport {Provider} from "react-redux"\nimport {store} from "./store";\nimport React from "react";\n\nexport default function ReduxProvider({children}: { children: React.ReactNode }) {\n return <Provider store={store}>{children}</Provider>;\n};\nRun Code Online (Sandbox Code Playgroud)\n在你的布局中:
\nimport './globals.css'\nimport type { Metadata } from 'next'\nimport { Inter } from 'next/font/google'\nimport ReduxProvider from "@/app/store/ReduxProvider";\n\nconst inter = Inter({ subsets: ['latin'] })\n\nexport const metadata: Metadata = {\n title: 'Create Next App',\n description: 'Generated by create next app',\n}\n\nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n <html lang="en">\n <body className={inter.className}>\n <ReduxProvider>\n {children}\n </ReduxProvider>\n </body>\n </html>\n )\n}\n\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
5691 次 |
| 最近记录: |