【问题标题】:Property 'menuInfo' does not exist on type 'ModeContextType | undefined'. TS2339类型'ModeContextType | 上不存在属性'menuInfo'不明确的'。 TS2339
【发布时间】:2021-11-04 06:21:09
【问题描述】:

我正在尝试使用带有打字稿的 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 (

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    您已将上下文键入为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,
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 2017-12-31
      • 2016-03-14
      • 2017-02-25
      • 2021-11-24
      • 2019-01-11
      • 2021-05-08
      • 2021-10-15
      • 2021-05-18
      相关资源
      最近更新 更多