第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Typescript React createContext 和 useState

Typescript React createContext 和 useState

Qyouu 2023-11-02 19:56:19
我是 TS 的新手,正在嘗試更新我從前員工那里繼承的代碼。我知道它與 TS 相關(guān),并且嘗試了不同類型但無法解決它。任何幫助都會(huì)很棒。提前致謝。這是代碼: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;};錯(cuò)誤截圖:https://i.stack.imgur.com/YKbri.png
查看完整描述

1 回答

?
ibeautiful

TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊

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

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


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


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

或者,如果它始終應(yīng)該是一個(gè)數(shù)字,您也可以這樣做,但您需要提供一個(gè)數(shù)字的初始值:


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

PS:這與您的問題無關(guān),但我注意到這段代碼使用了一個(gè)常見錯(cuò)誤:您在每次渲染上創(chuàng)建一個(gè)全新的對(duì)象并將其作為上下文值傳遞。


value={{ history, setHistory }}>

由于每次渲染都有一個(gè)新值,因此即使歷史記錄和 setHistory 沒有更改,它也會(huì)強(qiáng)制消耗上下文的任何內(nèi)容重新渲染。要解決此問題,您應(yīng)該記住該值,以便僅在實(shí)際更改時(shí)重新計(jì)算它:


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

    return { history, setHistory };

  }, [history]);


  return (

    <HistoryContext.Provider value={value}>

      {children}

    </HistoryContext.Provider>

  );


查看完整回答
反對(duì) 回復(fù) 2023-11-02
  • 1 回答
  • 0 關(guān)注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)