无法调用可能是 'null' 上下文的对象

Cannot invoke an object which is possibly 'null' context

为什么我会收到此 ts 错误:

Cannot invoke an object which is possibly 'null'.

Context.tsx

import React, { createContext, useState } from 'react';

type ForgotPasswordProviderProps = {
  children: React.ReactNode;
}

export type Email = {
  email: string | null;
  setEmail: React.Dispatch<React.SetStateAction<string>> | null;
}

export const ForgotPasswordContext = createContext<Email | null>(null);

export const ForgotPasswordContextProvider = ({
  children
}: ForgotPasswordProviderProps) => {
  const [email, setEmail] = useState('');
  return <ForgotPasswordContext.Provider value={{email, setEmail}}>{children}</ForgotPasswordContext.Provider>
}

ForgotPassword.tsx

  const handleChangeEmail = (e: string) => (emailContext && emailContext.setEmail('asas');

在线出现此错误:emailContext.setEmail

我该如何解决这个问题?

你的上下文定义了这个类型:

export type Email = {
  email: string | null;
  setEmail: React.Dispatch<React.SetStateAction<string>> | null;
}

这表示 setEmail 属性 可以是状态 setter 函数,也可以是 null.

这意味着当你执行这个:

emailContext && emailContext.setEmail('asas')

那么 emailContext.setEmail 可能是 null.

要修复它,您需要在使用前验证 属性 是否有值。您可以使用可选的链接运算符 ?. 在此处安全地钻取:

emailContext?.setEmail?.('asas')