出于某种原因,我无法运行我的 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' 没有重叠。
我真的不知道这意味着什么以及如何解决它。
只有当我像这样在对象数组中指定数字时,它才会起作用:
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/