我最近看到了 Jack Herrington 的 youtube 視頻,“Mastering React Context”,他將其用作useState背景關系提供者的值。這讓我覺得很有趣,但是當我嘗試用 typescript 做同樣的事情時,我完全被如何輸入初始狀態所困擾。
示例 JS 代碼:
const CounterContext = createContext(null);
const CounterContextProvider = ({children}) => {
return (
<CounterContext.Provider value={useState(0)}>
{children}
</CounterContext.Provider>
}
使用null默認值是不可能的。我可以定義正確的型別,useState但初始狀態值會是什么樣子?
uj5u.com熱心網友回復:
回傳的值useState(0)是一個型別為 的元組[number, Dispatch<SetStateAction<number>>],其中Dispatch和SetStateAction是從 react 匯入的。因此,使用模擬默認值,將如下所示:
import { createContext, Dispatch, SetStateAction } from "react";
const CounterContext = createContext<
[number, Dispatch<SetStateAction<number>>]
>([0, () => {}]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462369.html
