Ilj*_*lja 6 typescript reactjs react-hooks
我无法弄清楚如何输入useState函数,因为它返回一个元组.本质上,我必须提供ie的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>
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
Sea*_*ary 17
这已经在几个地方得到解决:
https://dev.to/busypeoples/notes-on-typescript-react-hooks-28j2
https://codewithstyle.info/Using-React-useState-hook-with-TypeScript/
TLDR:当初始状态为空时,将类型参数传递给 setState
例如:
const [email, setEmail] = useState<string>();
Run Code Online (Sandbox Code Playgroud)
Nur*_*yev 13
你可以尝试一下,告诉我它是否有效吗?
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>
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5916 次 |
| 最近记录: |