Reactjs 使用React';时键入可为空状态的正确方法;使用状态挂钩

Reactjs 使用React';时键入可为空状态的正确方法;使用状态挂钩,reactjs,typescript,react-hooks,Reactjs,Typescript,React Hooks,我在计算如何键入useState函数时遇到困难,因为它返回一个元组。本质上,我必须提供null作为email的初始值,也就是说,假设我不能在这里使用空字符串 然后我使用setEmail函数来更新这个状态值,它将email作为字符串接收 理想情况下,我希望键入我的useState,因此它希望电子邮件可能是字符串或null。此时,它仅将其继承为null import * as React from "react"; const { useState } = React; function Exa

我在计算如何键入
useState
函数时遇到困难,因为它返回一个元组。本质上,我必须提供
null
作为
email
的初始值,也就是说,假设我不能在这里使用空字符串

然后我使用
setEmail
函数来更新这个状态值,它将email作为字符串接收

理想情况下,我希望键入我的
useState
,因此它希望电子邮件可能是字符串或null。此时,它仅将其继承为
null

import * as React from "react";

const { useState } = React;

function Example() {
  const [state, setState] = useState({ email: null, password: null });

  function setEmail(email: string) {
    setState(prevState => ({ ...prevState, email }))
  }

  return <p>{state.email}</p>
}

目前,TypeScript编译器认为
电子邮件
密码
的类型是
null
(没有其他值)。您可以通过向
useState
调用提供显式类型参数来解决此问题,以便
电子邮件
密码
的类型已知为
字符串

const { useState } = React;

function Example() {
  const [state, setState] = useState<{email: null | string, password: null | string}>({ email: null, password: null });

  function setEmail(email: string) {
    setState(prevState => ({ ...prevState, email }))
  }

  return <p>{state.email}</p>
}
const{useState}=React;
函数示例(){
const[state,setState]=useState({email:null,password:null});
函数setEmail(电子邮件:字符串){
setState(prevState=>({…prevState,email}))
}
返回{state.email}

}
您可以使用TS映射类型来提高可读性,并且更喜欢未定义的值而不是空值

const { useState } = React;

function Example() {
  const [state, setState] = useState<Partial<{email: string, password: string}>>();

  function setEmail(email: string) {
    setState(prevState => ({ ...prevState, email }))
  }

  return <p>{state.email | ""}</p>
}
const{useState}=React;
函数示例(){
const[state,setState]=useState();
函数setEmail(电子邮件:字符串){
setState(prevState=>({…prevState,email}))
}
返回{state.email |“”}

}
这已经在一些地方得到了解决:

TLDR:当初始状态为空时,将类型参数传递给setState

例如:

const[email,setEmail]=useState();

用空字符串更改null时会发生什么情况?我的意思是,如果您使用
useState({email:,password:})
?@lomse进行排序,但正如我在问题中提到的,我想找出一种使用
someType | null
方法的方法,即如果我将来使用自定义接口,但希望初始值为null或未定义,我认为您应该对接受的答案进行注释/编辑,因为您的答案可读性较差,并且不会为现有的接口提供额外的好处答案。考虑到使用更少的字符,我认为这个解决方案更好:重复
null | xxx
四次并不能提高可读性?拥有
null
属性和根本没有属性是不一样的。使用分部实际上是个好主意,并帮助我:)我不理解否决票。比公认的答案干净多了。物体呢?
const { useState } = React;

function Example() {
  const [state, setState] = useState<Partial<{email: string, password: string}>>();

  function setEmail(email: string) {
    setState(prevState => ({ ...prevState, email }))
  }

  return <p>{state.email | ""}</p>
}
const [email, setEmail] = useState<string>();