使用React的useState钩子时正确的输入可为空状态的方法

时间:2018-11-16 13:34:13

标签: reactjs typescript react-hooks

我很难弄清楚如何键入useState函数,因为它返回一个元组。本质上,我必须提供null作为email的初始值,即假设我不能在此处使用空字符串。

然后我有setEmail函数来更新此状态值,该状态值将电子邮件作为字符串输入。

理想情况下,我想输入我的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>
}

对于setEmail函数,将返回以下错误,因为函数自变量中的string对于null中指定的useState()而言不是有效的类型

[ts]
Argument of type '(prevState: { email: null; password: null; }) => { email: string; password: null; }' is not assignable to parameter of type 'SetStateAction<{ email: null; password: null; }>'.
  Type '(prevState: { email: null; password: null; }) => { email: string; password: null; }' is not assignable to type '(prevState: { email: null; password: null; }) => { email: null; password: null; }'.
    Type '{ email: string; password: null; }' is not assignable to type '{ email: null; password: null; }'.
      Types of property 'email' are incompatible.
        Type 'string' is not assignable to type 'null'. [2345]
(parameter) prevState: {
    email: null;
    password: null;
}

3 个答案:

答案 0 :(得分:9)

已经在几个地方解决了这个问题:

https://dev.to/busypeoples/notes-on-typescript-react-hooks-28j2

https://codewithstyle.info/Using-React-useState-hook-with-TypeScript/

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

例如:

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let bool = Target.current == .targetOne
        let targetBasedViewController: UIViewController = bool ? FirstViewController() : SecondViewController()
        targetBasedViewController.tabBarItem.title = bool ? "First" : "Second"
        targetBasedViewController.tabBarItem.image = UIImage(named: bool ? "First" : "Second")
    }
}

答案 1 :(得分:6)

您能尝试一下并告诉我是否可行吗?

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>
}

答案 2 :(得分:0)

您可以使用TS映射类型来提高可读性,并且首选使用undefined而不是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>
}