【问题标题】:TypeScript Interfaces: Property 'A' does not exist on type 'B | null'TypeScript 接口:类型“B”上不存在属性“A”|空值'
【发布时间】:2021-07-14 04:35:02
【问题描述】:

我正在尝试将 TypeScript 接口类型添加到我正在提取的 JSON 数据中。我目前收到以下与我的 MachineDetail.tsx 文件相关的错误:

Property 'data' does not exist on type 'APIContextInterface | null'.

MachineDetail.tsx(下面的行是引发错误的地方)

const { data, isLoading } = useContext(APIContext);

apiContext.tsx(我在其中提取 API 数据并将其存储在 Context 中)

我的 TypeScript 界面和我保存数据的上下文:

import React, { useState, useEffect, createContext } from "react";
import axios from "axios";

interface APIContextInterface {
  category: string;
  product_details: {
    id: number;
    category: string;
    model: string;
    power: number;
    operating_weight: number;
    description: string;
    image: string;
  };
}

export const APIContext = createContext<APIContextInterface | null>(null);
   
export default function APIContextProvider({ children }) {
  // Initialize state
  const [data, setData] = useState([]);
  const [isLoading, setLoading] = useState(true);

  // Fetch data
  useEffect(() => {
    let url = "../db.json";
    axios
      .get(url)
      .then(function (response) {
        setData(response.data.machines);
        setLoading(false);
      })
      .catch((error) => console.log(error));
  }, []);

  return (
    <APIContext.Provider value={{ data, isLoading }}>
      {children}
    </APIContext.Provider>
  );
}

JSON 数据的结构如下:

{
    "machines": [{
            "category": "category name",
            "product_details": [{
                    "id": 1,
                    "category": "category name",
                    "model": "224X3",
                    "power": 67.1,
                    "operating_weight": 5849,
                    "description": "desc goes here",
                    "image": "url-link"
                },
             ],
          },
     ]
}

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    这是因为您将APIContext 定义为包含APIContextInterface | null 的上下文:

    export const APIContext = createContext<APIContextInterface | null>(null);
    

    而您实际上提供了另一种类型的值。请记住,您提供给createContext 的类型始终是您应该提供的类型。因此你应该写

    export const APIContext = createContext<{
      data: APIContextInterface[],
      isLoading: boolean
    } | null>(null);
    

    而是为了匹配您的实际数据。

    【讨论】:

      【解决方案2】:

      引发此错误是因为在创建上下文后,您的 useState 可以创建单独的状态,而不是将其添加到您创建的上下文中。

      您可以从此答案中找到解决方案:Passing state with useContext in Typescript

      【讨论】:

        猜你喜欢
        • 2020-01-07
        • 1970-01-01
        • 1970-01-01
        • 2022-11-16
        • 2023-04-02
        • 2018-08-17
        • 1970-01-01
        • 2023-02-06
        • 2019-06-28
        相关资源
        最近更新 更多