使用打字稿将 setState 作为参数传递给 react/next.js 中的自定义挂钩

Passing setState as argument to custom hook in react/next.js with typescript

这是给我一个错误的代码:

import { useState, useEffect } from "react";

type Props = {
  setState: (value: string) => void;
};

const useSomeCustomHook = ({ setState }: Props) => {
  useEffect(() => {
    setState("updated value");
  }, []);
};

const SomePage = () => {
  const [state, setState] = useState("initial value");

  useSomeCustomHook(setState);
};
export default SomePage;

我试图将 setState 函数作为参数传递给自定义挂钩,但出现此错误:

Argument of type 'Dispatch<SetStateAction<string>>' is not assignable to parameter of 
type 'Props'.
Property 'setState' is missing in type 'Dispatch<SetStateAction<string>>' but required 
in type 'Props'.

我尝试用常规函数切换自定义挂钩,这奏效了。这是否意味着我不了解有关自定义挂钩的某些内容?从报错来看,好像是道具类型有问题?

您希望将对象传递给 useCustomHook 但您使用函数调用它。 如果您不想更改 Props 或希望以后有更多道具,请像这样使用它:

const SomePage = () => {
  const [state, setState] = useState("initial value");

  useSomeCustomHook({setState});
};

React 中有 setState 的定义。

因此您需要像下面这样定义 setState 函数的类型。

type Props = {
  setState: Dispatch<SetStateAction<string>>;
};

const useSomeCustomHook = ({ setState }: Props) => {
  useEffect(() => {
    setState("updated value");
  }, []);
};

const SomePage = () => {
  const [state, setState] = useState("initial value");

  useSomeCustomHook({setState});
};
export default SomePage;