reactjs typescript 错误:无法将类型为“()=>()=>Socket〈DefaultEventsMap,DefaultEventsMap>”的参数分配给类型为“EffectCallback”的参数

ljo96ir5  于 2022-11-29  发布在  React
关注(0)|答案(1)|浏览(247)

我很难理解我应该用什么类型约束来避免在我的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)
41zrol4v

41zrol4v1#

编辑:解决了这个问题。错误是我像return () => newSocket.close();那样做清理,结果返回了一个Socket<DefaultEventsMap, DefaultEventsMap>类型。
解决方案是将newsocket.close()调用放在花括号内,这样返回值保持为空,如下所示:

return () => {
  newSocket.close();
};

如果我的解释有错的话,我希望能得到进一步的解释。

相关问题