[英]Generic props : why are these types incompatible?
我有兩個帶有帶有通用參數TVariables
的道具的 React 組件。 這些道具具有以下字段:類型TVariables
的variables
和類型為(vars: TVariables) => void
setVariables
setVariables。
當我像這樣使用我的組件時:
const [variables, setVariables] = useState({ ...someProperties })
<A variables={variables} setVariables={setVariables}/>
我希望組件A
能夠推斷出TVariables
,因此這兩個道具都可以工作。 但是設置setVariables
時出現不兼容錯誤。
這個描述非常晦澀,而且 typescript 錯誤報告更多,所以我創建了一個極簡的代碼框演示:
為什么會出現這些錯誤,我該如何解決? 謝謝你。
您應該為 setVariables 使用類型React.Dispatch<React.SetStateAction<TVariables>>
setVariables
Set state functions in React can passed the new value for the state variable, but can also be passed a callback function that updates the state variable. 因此類型(variables: TVariables) => void
與 React 集 state function 的類型不匹配。
似乎 Typescript 抱怨因為您在初始 state 中聲明的這兩個變量
test: "demo",
sortOrder: -1,
如果將它們添加到ListVariables
,錯誤就會消失:
type ListVariables = {
limit: number;
page: number;
test: string;
sortOrder: number;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.