網站搜尋

javascript - useState 設定函數的類型是什麼?


有時候,useState 鉤子的設定函數必須被傳遞。對這個函數正確的類型標註方式是什麼?

// some component with useState
const [infoText, setInfoText] = useState<string>(""); 

// same component calls a function in which the setter function is needed.
getInfoText(setInfoText);

// in the definition of that function (getInfoText) I now want to correctly type the setter function
export function getInfoText(setInfoText: ???) {

附註:我知道有幾個類似的問題。我想提出一個沒有上下文的一般問題,例如:這段程式碼的正確類型是什麼。

答案#1

在 React 中,狀態設定函數的類型是 Dispatch<SetStateAction<TypeOfTheState>>,其中 Dispatch 和 SetStateAction 可以從 "react" 匯入。例如:

import { Dispatch, SetStateAction, useState } from "react";

export default function Component() {
  // The type of setInfoText is Dispatch<SetStateAction<string>>
  const [infoText, setInfoText] = useState<string>("");

  // We can give it as an argument to foo, as it's typed below
  foo(setInfoText);

  return <></>;
}

function foo(stateSetter: Dispatch<SetStateAction<string>>) {}