完整错误: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 中突出显示的内容)。
所以问题是当我在承诺的 useState
部分使用 setMyState then()
钩子时。我知道我错误地定义了我的类型,因为我看到了一个错误,但是这个错误让我感到困惑;什么是 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);
}
答案 0 :(得分:2)
您正在呼叫 setLoggedIn
立即。这:
<button type="submit" onClick={() => auth.logout().then(setLoggedIn(false))}>
就像在做
const parameterToPassToThen = setLoggedIn(false);
<button type="submit" onClick={() => auth.logout().then(parameterToPassToThen)}>
这没有意义。
同一问题的另一个例子,在 React 之外:
const prom = new Promise((resolve) => setTimeout(resolve, 2000));
console.log('starting');
prom.then(console.log('resolved'));
// `resolved` is printed immediately, not 2 seconds later
.then
应该总是接受一个 函数:
<button type="submit" onClick={() => auth.logout().then(() => { setLoggedIn(false); })}>