gpt4 book ai didi

reactjs - 使用 React 的 useState 钩子(Hook)时输入可空状态的正确方法

转载 作者:搜寻专家 更新时间:2023-10-30 20:54:03 24 4
gpt4 key购买 nike

我无法弄清楚如何键入 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 不是 useState() 中指定的 null 的有效类型

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

最佳答案

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

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

关于reactjs - 使用 React 的 useState 钩子(Hook)时输入可空状态的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53338922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com