我很难理解我应该用什么类型约束来避免在我的useEffect
中出现这个错误。一个解决方案是转换我的newSocket
或将我的useEffect
返回值输入为any
,但我认为这是不可行的。
我的代码:
import React, { useContext, useEffect, useState } from "react";
import type { Socket } from "socket.io-client";
import io from "socket.io-client";
interface SocketProviderInterface {
id: string;
children: JSX.Element;
}
const SocketContext = React.createContext<Socket | null>(null);
export const useSocket = () => {
return useContext(SocketContext);
};
export const SocketProvider = ({ id, children }: SocketProviderInterface) => {
const [socket, setSocket] = useState<Socket | null>(null);
useEffect(() => {
const newSocket = io(`http://localhost:3333`, { query: { id } });
setSocket(newSocket);
return () => newSocket.close();
}, [id]);
return (
<SocketContext.Provider value={socket}>{children}</SocketContext.Provider>
);
};
我的错误:
function(): () => Socket<DefaultEventsMap, DefaultEventsMap>
Argument of type '() => () => Socket<DefaultEventsMap, DefaultEventsMap>' is not assignable to parameter of type 'EffectCallback'.
Type '() => Socket<DefaultEventsMap, DefaultEventsMap>' is not assignable to type 'void | Destructor'.
Type '() => Socket<DefaultEventsMap, DefaultEventsMap>' is not assignable to type 'Destructor'.
Type 'Socket<DefaultEventsMap, DefaultEventsMap>' is not assignable to type 'void | { [UNDEFINED_VOID_ONLY]: never; }'.ts(2345)
1条答案
按热度按时间41zrol4v1#
编辑:解决了这个问题。错误是我像
return () => newSocket.close();
那样做清理,结果返回了一个Socket<DefaultEventsMap, DefaultEventsMap>
类型。解决方案是将
newsocket.close()
调用放在花括号内,这样返回值保持为空,如下所示:如果我的解释有错的话,我希望能得到进一步的解释。