【发布时间】:2021-02-07 16:05:15
【问题描述】:
完整错误:TS2345: Argument of type 'void' is not assignable to parameter of type '((value: boolean) => boolean | PromiseLike<boolean>) | null | undefined'.
有问题的行是这一行:<button type="submit" onClick={() => auth.logout().then(setLoggedIn(false))}>
特别是 TypeScript 不喜欢 setLoggedIn(false)(这是 IDE 中突出显示的内容)。
所以问题是当我在承诺的then() 部分使用 setMyState useState 钩子时。我知道我定义了错误的类型,因为我看到了一个错误,但是这个错误让我感到困惑; argument of type void 是什么,因为 setLoggedIn 需要一个布尔值。
我的代码:
Main.tsx
const [isLoggedIn, setLoggedIn] = useState<boolean>(false);
<UserLoginForm isLoggedIn={isLoggedIn} setLoggedIn={setLoggedIn} />
UserLoginForm.tsx
import React, { useEffect } from 'react';
import getAuthClient from '../utils/auth';
const auth = getAuthClient();
interface MyProps {
isLoggedIn: boolean,
setLoggedIn: React.Dispatch<React.SetStateAction<boolean>>,
}
const UserLoginForm: React.VFC<MyProps> = ({ isLoggedIn, setLoggedIn }: MyProps) => {
if (isLoggedIn) {
return (
<div>
<p>You are currently logged in.</p>
<button type="submit" onClick={() => auth.logout().then(setLoggedIn(false))}>
Log out
</button>
</div>
);
}
auth.tsx
/**
* Delete the stored OAuth token, effectively ending the user's session.
*/
function logout(): Promise<boolean> {
localStorage.removeItem(updatedConfig.token_name);
return Promise.resolve(true);
}
【问题讨论】:
标签: reactjs typescript react-typescript