gpt4 book ai didi

reactjs - 此表达式不可调用。 '{}' 类型没有调用签名。 TS2349

转载 作者:行者123 更新时间:2023-12-04 16:39:59 24 4
gpt4 key购买 nike

一个很常见的 TypeScript 错误 TS2349,即 sth has no call signatures .
在不同的情况下,它使用不同的变通方法来解决。但是处理 react 的上下文,我发现的最佳解决方案是使用 // @ts-ignore .
请问,在这种情况下正确的方法是什么?

// auth.tsx

import { CurrentUserContext } from 'components/currentUser';
import React, { useState, useEffect, useContext } from 'react';

const Auth = ({ onLogin }: {onLogin: any}) => {

const [, setCurrentUserState] = useContext(CurrentUserContext);
const [credentials, { data }] = useMutation(AUTH);

...

useEffect(() => {
if (data) {

// TypeScript Error without @ts-ignore:
// This expression is not callable.
// Type '{}' has no call signatures. TS2349

// @ts-ignore
setCurrentUserState((state: any) => ({
...state,
currentUser: data.login.author,
}))
}
}, [data, setCurrentUserState]);

return <div>{data.login.author}</div>
}

// currentUser.tsx

import React, { createContext, useState } from 'react';

const CurrentUserContext = createContext([{}, () => {}]);

const CurrentUserProvider = ({ children }: {children: any}) => {
const [state, setState] = useState({
currentUser: null,
})
return (
<CurrentUserContext.Provider value={[state, setState]}>
{ children }
</CurrentUserContext.Provider>
)
};

export {
CurrentUserContext,
CurrentUserProvider,
}
不详“ react ”:“^16.13.1”
“ typescript ”:“~3.7.2”

最佳答案

描述并明确指定类型:

type IUserState = {
currentUser?: object;
};

type ICurrentUserContext = [IUserState, React.Dispatch<React.SetStateAction<IUserState>>];

const CurrentUserContext = React.createContext<ICurrentUserContext>([{}, () => null]);

const CurrentUserProvider = ({ children }: { children: any }) => {
const [state, setState] = useState<IUserState>({
currentUser: null,
});

return <CurrentUserContext.Provider value={[state, setState]}>{children}</CurrentUserContext.Provider>;
};

关于reactjs - 此表达式不可调用。 '{}' 类型没有调用签名。 TS2349,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62932775/

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