首页 > 解决方案 > 带有打字稿的 Next.js - useContext 错误

问题描述

我正在开发一个应用程序,对于我正在使用 next.js 的前端,我在尝试对对象进行字符串化时遇到问题,这就是错误的样子

Argument of type '{ auth: dataObject; }' is not assignable to parameter of type 'string'

所以发生的情况是,当用户登录时,我试图保存一些数据 localStorage,据我所知,如果你在那里保存数据,它必须是一个字符串(我真的不知道为什么)所以这就是为什么我正在使用 json.stringify (在我的代码中)。

现在,为了给你更多的上下文,让我给你看我的代码

这是我的上下文 - useReducer 部分(问题出在 LOGIN 案例中!)

import { createContext } from "react";

import {
  Actions,
  dataObject,
  LOGIN,
  LOGOUT,
  LOADING
} from "../GlobalInterfaces/AuthContextInterfaces";
import { useReducer } from "react";
import { useContext } from "react";

interface Istate {
  loading: boolean;
  data?: dataObject | null;
}

const DefaultState = createContext<Istate>({ loading: false });

const DispatchActions = createContext(null);

const localReducer = (state: Istate, action: Actions): Istate => {
  switch (action.type) {
    case LOADING:
      return {
        ...state,
        loading: true
      };

    case LOGIN:
      JSON.stringify(localStorage.setItem("Auth", { auth: action.payload }));
      return {
        ...state,
        loading: false,
        data: action.payload
      };

    case LOGOUT:
      localStorage.removeItem("Auth");
      return {
        ...state,
        data: null
      };

    default:
      return state;
  }
};

export const AuthContext = ({ children }: { children: React.ReactNode }) => {
  const [state, dispatch] = useReducer(localReducer, {
    loading: false,
    data: null
  });

  return (
    <DefaultState.Provider value={state}>
      <DispatchActions.Provider value={dispatch}>
        {children}
      </DispatchActions.Provider>
    </DefaultState.Provider>
  );
};

export const AuthData = () => useContext(DefaultState);
export const AuthActions = () => useContext(DispatchActions);

这些是我与 useContext 和 useReducer 一起使用的类型和接口

// Data

export type dataObject = {
  token: string;
  user: { id: string; email: string; name: string };
};

// Options's Actions

export const LOGIN = "LOGIN";
export const LOGOUT = "LOGOUT";
export const LOADING = "LOADING";

interface IloginAuth {
  type: typeof LOGIN;
  payload: dataObject;
}

interface IloginLogout {
  type: typeof LOGOUT;
}

interface Iloading {
  type: typeof LOADING;
}

export type Actions = IloginAuth | IloginLogout | Iloading;

那么我该怎么做才能修复我的代码?我可以跳过 JSON.stringify 吗?

谢谢你的时间 !

标签: reactjstypescriptnext.js

解决方案


JSON.stringify(localStorage.setItem("Auth", { auth: action.payload }));

setItem 的第二个参数需要是一个字符串。你在一个对象中传递它。您需要以相反的顺序执行这些操作。

localStorage.setItem("Auth", JSON.stringify({ auth: action.payload }));

推荐阅读