簡體   English   中英

類型 'ModeContextType | 上不存在屬性 'menuInfo' 不明確的'。 TS2339

[英]Property 'menuInfo' does not exist on type 'ModeContextType | undefined'. TS2339

我正在嘗試使用帶有打字稿的 React 鈎子的上下文。 我不知道我哪里做錯了。

export interface IPayload {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [key: string]: any;
}

export interface ModeContextType {
  menuInfo: IPayload;
  modeData: IPayload;
  currentModeCode: number;
  setCurrentModeCode: (arg0: string) => void;
}

export const ModeContext = createContext<ModeContextType | undefined>(undefined);
  const modeContextValue = {
    menuInfo: menuInfo,
    modeData: modeData,
    currentModeCode: currentModeCode,
    setCurrentModeCode: setCurrentModeCode,
  };

  return (
    <>
      <ModeContext.Provider value={modeContextValue}>
        <Header currentModeCode={currentModeCode} />
        <div className="thumbnail-block" ref={thumbnailBlock}>
          {listOfThumbnails}
        </div>
        <div id="detail-set-block">
          <DetailCampaign key={currentCampaignCode} info={currentCampaign} />
        </div>
        <div className="clearfix">
          <button id="see-all" type="button" className="btn btn-dark">
            {t("top.see_all_product_at_this_fair")}
          </button>
        </div>
        <Category />
      </ModeContext.Provider>
    </>
  );

在子組件中,我使用useContext如下

function Category(): JSX.Element {
  const { menuInfo, modeData, currentModeCode, setCurrentModeCode } = useContext(ModeContext);

錯誤是

Property 'menuInfo' does not exist on type 'ModeContextType | undefined'.  TS2339

     6 | 
     7 | function Category(): JSX.Element {
  >  8 |   const { menuInfo, modeData, currentModeCode, setCurrentModeCode } = useContext(ModeContext);
       |           ^
     9 |   // const modeData = getMode(menuInfo);
    10 |   const listOfModes = Object.entries(modeData).map(([modeCode, modeInfo]) => {
    11 |     return (

您已將上下文鍵入為ModeContextType | undefined ModeContextType | undefined ,它的默認值是undefined 這意味着您不能假設您正在解構的屬性確實存在。

您收到的錯誤是因為該聯合類型的所有成員都不存在menuInfo ,因為這些成員是undefined

因此,您可能需要執行以下操作:

const modeContextValue = useContext(ModeContext);
if (modeContextValue) {
  { menuInfo, modeData, currentModeCode, setCurrentModeCode } = modeContextValue
  // other code that can run when modeContextValue has a value.
}

或者也許從上下文類型中刪除undefined並提供一組完整的默認值:

export const ModeContext = createContext<ModeContextType>({
  menuInfo: {},
  modeData: {},
  currentModeCode: 0,
  setCurrentModeCode: () => undefined,
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM