seToken与useContext粘贴在useReducer中

seToken与useContext粘贴在useReducer中

本文介绍了在nextjs中将useToken与useContext粘贴在useReducer中,并获得未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Next.js中将 useReducer useContext 结合使用时遇到问题.我想使用用户已经通过 useReducer useContext 制作的令牌,但是当我尝试使用它时,它是不确定的.我不知道该怎么办?

I have problem using useReducer with useContext in Next.js. I want to use the token that the user have already make with useReducer and useContext, but when I try it is undefined. I don't know what should I do?

这是我的代码文件:

这是我的 AuthToken.js 文件:

import React, { createContext, useEffect, useReducer } from 'react';
// Create context
export const AuthToken = createContext();

const initialState = {
    auth: {},
    user: []
};

const ACTIONS = {
    AUTH: "AUTH",
    ADD_USERS: "ADD_USERS"
};

const reducer = (stateAuth, action) => {
    switch(action.type) {
        case ACTIONS.AUTH:
            return {
                ...stateAuth,
                auth: action.payload
            };
        case ACTIONS.ADD_USERS:
            return {
                ...stateAuth,
                user: action.payload
            };
        default:
            return stateAuth;
    };
};

export function DataProvider({children}) {
    const {stateAuth, dispatchAuth} = useReducer(reducer, initialState);

    useEffect(() => {
        const firstLogin = localStorage.getItem("firstLogin");
        if (firstLogin === true) {
            async (token) => {
                const res = await fetch("http://localhost:3000/api/users/", {
                    method: "GET",
                    headers: {
                        "Authorization": token
                    }
                });
                await res.json().then(res => {
                    res.err ? localStorage.removeItem("firstLogin") : dispatchAuth({
                        type: ACTIONS.AUTH,
                        payload: {
                            token: res.accessToken,
                            user: res.user
                        }
                    });
                });
            };
        };
    }, []);

    return (
        <AuthToken.Provider value={{stateAuth, dispatchAuth}}>
            {children}
        </AuthToken.Provider>
    );
};

此代码用于从Next.js的api文件夹中获取令牌(无论如何,我正在使用 next-connect ):

This code for get the token from api folder in Next.js (anyway I'm using next-connect):

import dbConnect from '../../../utils/dbConnect';
import User from '../../../model/User';
import handler from '../../../components/handler';
import { hash } from 'bcrypt';
import jwt from 'jsonwebtoken';
import { createAccessToken } from "../../../utils/generateToken";

dbConnect();

export default handler.get(async (req, res) => {
    try {
        const token = req.cookies.auth;
        if (!token) return res.status(400).json({ message: "Please Login To Get Access" });

        const result = jwt.verify(token, process.env.JWT_REFRESH_TOKEN);
        if (!result) return res.status(400).json({ message: "Token Has Been Expired" });

        const user = await User.findById(result.userId);
        if (!user) return res.status(400).json({ message: "User Does Not Exist" });

        const accessToken = createAccessToken({ id: user._id });
        res.status(200).json({ accessToken, user: {
            userId: user._id,
            myUserName: user.nama,
            myUserEmail: user.email
        }});
    } catch(err) {
        res.status(500).json({ message: "Server Error", err: err.message });
    };
})

这是我的 _app.js :

import "../styles/globals.css";
import { DataProvider } from "../utils/AuthToken";

function MyApp({ Component, pageProps }) {
    return (
        <DataProvider>
            <Component {...pageProps} />
        </DataProvider>
    );
};

export default MyApp

这是我的 index.js (我想在这里使用令牌):

And this is my index.js (I want use the token here):

import React, { useContext } from 'react';
import Head from 'next/head';
import { AuthToken } from "../utils/AuthToken";

function Home() {
    const { stateAuth, dispatchAuth } = useContext(AuthToken);
    console.log(stateAuth, dispatchAuth); // When i console log it i get undefined for both of them. That's my problem is.

    return (
        <React.Fragment>
            <Head>
                <title>Try useContext and useReducer</title>
                <meta name="icon" href="/favicon.ico" />
            </Head>
        </React.Fragment>
    );
};

export default Home;

这是我的问题:浏览器上的 console.log 不确定.

This is my problem: console.log on the browser gets undefined.

推荐答案

useReducer 钩子返回一个元组,但是您正在将其作为对象进行销毁.正确的语法如下:

The useReducer hook returns a tuple, but you're destructuring it as an object. The proper syntax would look like:

const [stateAuth, dispatchAuth] = useReducer(reducer, initialState);

这篇关于在nextjs中将useToken与useContext粘贴在useReducer中,并获得未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:42