亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Typescript React createContext 和 useState

Typescript React createContext 和 useState

Qyouu 2023-11-02 19:56:19
我是 TS 的新手,正在嘗試更新我從前員工那里繼承的代碼。我知道它與 TS 相關,并且嘗試了不同類型但無法解決它。任何幫助都會很棒。提前致謝。這是代碼:import React from 'react';export interface HistoryType {  history?: number;  setHistory: (value: number) => void;}const HistoryContext = React.createContext<HistoryType | undefined>(undefined);export const HistoryProvider: React.FC = ({ children }) => {  const [history, setHistory] = React.useState();  return (    <HistoryContext.Provider value={{ history, setHistory}}>      {children}    </HistoryContext.Provider>  );};export const useHistoryState = () => {  const context = React.useContext(HistoryContext);  if (context === undefined) {    throw new Error('useHistoryState error');  }  return context;};錯誤截圖:https://i.stack.imgur.com/YKbri.png
查看完整描述

1 回答

?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

const [history, setHistory] = React.useState()

由于此處未指定類型,因此打字稿必須嘗試推斷它。它看到undefined被隱式傳遞給 use state,因此它假設狀態是(并且永遠是)undefined。那么這意味著setHistory期望能夠通過undefined。


您需要自己指定類型,以表示它可以是數字,也可以是未定義的:


const [history, setHistory] = React.useState<number | undefined>();

或者,如果它始終應該是一個數字,您也可以這樣做,但您需要提供一個數字的初始值:


const [history, setHistory] = React.useState<number>(42);

PS:這與您的問題無關,但我注意到這段代碼使用了一個常見錯誤:您在每次渲染上創建一個全新的對象并將其作為上下文值傳遞。


value={{ history, setHistory }}>

由于每次渲染都有一個新值,因此即使歷史記錄和 setHistory 沒有更改,它也會強制消耗上下文的任何內容重新渲染。要解決此問題,您應該記住該值,以便僅在實際更改時重新計算它:


  const value = React.useMemo(() => {

    return { history, setHistory };

  }, [history]);


  return (

    <HistoryContext.Provider value={value}>

      {children}

    </HistoryContext.Provider>

  );


查看完整回答
反對 回復 2023-11-02
  • 1 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號