javascript - TypeScript:属性 'name' 在类型 'any[]' 上不存在

标签 javascript reactjs typescript types react-hooks

出于某种原因,我无法运行我的 React 应用程序,因为以下错误:
TypeScript:类型“any[]”上不存在属性“name”。
我正在根据我的 API 数据导出我的 TS 类型:

export type CartItemType = {
  id: number;
  name: string;
  image: string;
  amount: number;
  chair: {
    name: string;
    colors: {
      white: {
        hex: string;
      };
    };
  };
};
获取数据:
  const getProducts = async (): Promise<CartItemType[]> =>
  await (await fetch("apiEndpoint")).json();

 const [cartItems, setCartItems] = useState([] as CartItemType[]);
 const { data, isLoading, error } = useQuery<CartItemType[]>(
    "products",
    getProducts
  );
我想选择获取的数据,我是这样做的:
const [selectedData, setSelectedData] = React.useState([]);

{data?.map((item) => (
            <button onClick={() => setSelectedData(item)}>SHOW</button>
{selectedData === item ? (
                <p>{selectedData.chair.description}</p>
 ) : null}
不幸的是,我在 selectedData 上遇到了这个错误:
此条件将始终返回 'false',因为类型 'any[]' 和 'CartItemType' 没有重叠。
我真的不知道这意味着什么以及如何解决它。
enter image description here
只有当我像这样在对象数组中指定数字时,它才会起作用:
selectedData[0].name
但我必须让它为 selectedData.name 工作

最佳答案

You must aware of the value that the state is going to hold. It is important because the state update cause the re-render of the application.


更改您的初始值 selectedData状态变量到 {} .
const [selectedData, setSelectedData] = React.useState({} as CartItemType);
原因:最初您在一个状态中保存数组值,然后您使用对象设置状态并假设它是一个对象并执行操作。因此,很明显您必须在 selectedData 中保存对象值。状态。
这就是您收到此错误消息的原因。
This condition will always return 'false' since the types 'any[]' and 'CartItemType' have no overlap.
好的部分:我在沙箱中进行了更改,错误消失了。

关于javascript - TypeScript:属性 'name' 在类型 'any[]' 上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68667526/

相关文章:

javascript - React 中的类分配

javascript - React Redux - 子组件不会在状态更改时重新渲染

typescript - WebStorm、空代码块和大括号

javascript - 为什么在 JSON 响应中使用类型

javascript - 使用 JavaScript 过滤 Firebase 查询

reactjs - 如何使用redux动态添加元素

javascript - Chrome 存储 : Unable to change component state from a callback function

typescript 类型 T 或函数 () => T 用法

javascript:对对象数组进行排序会得出不一致的结果

javascript - 在 React 应用程序中映射数组以优化性能的最佳实践