我正在學習 Typescript,并且正在將我的 React 專案轉換為 TS。但是,我遇到了一些障礙,我不太確定如何處理這個檔案:
import { Grid } from '@material-ui/core';
import { useParams } from 'react-router-dom';
// @ts-ignore
import ProductImage from './ProductImage.tsx';
// @ts-ignore
import ProductInfo from './ProductInfo.tsx';
type Props = {
products: {
id: number;
price: number;
description: string;
listing_type: string;
image: string;
}[];
addToCart: (e: MouseEvent) => void;
user: {
id: number;
isAuth: boolean;
};
}
const Product: React.FC<Props> = ({ products, addToCart, user }) => {
const { productId } = useParams<{productId: string}>()
const product = products.find(product => product.id === parseInt(productId));
return (
<div>
<Grid container spacing={1} style={{ maxWidth: 1100, margin: '0 auto', marginTop: '5rem' }}>
<Grid item sm={4}>
<ProductImage image={product?.image} />
</Grid>
<Grid item sm={8}>
<ProductInfo product={product} onClick={(e: React.MouseEvent<Element, globalThis.MouseEvent>) => addToCart(e)} user={user}/>
</Grid>
</Grid>
</div>
);
}
export default Product;
由于與匯入以 .tsx 結尾的檔案相關的錯誤,我添加了 @ts-ignore 行。但是,現在當我嘗試運行 npm start 時,出現以下錯誤:
TypeError: products.find is not a function
Product
src/components/products/ProductShow.tsx:27
24 | const Product: React.FC<Props> = ({ products, addToCart, user }) => {
25 | const { productId } = useParams<{productId: string}>()
26 | console.log(products)
> 27 | const product = products.find(product => product.id === parseInt(productId));
28 |
29 | return (
30 | <div>
(我應該注意到產品是作為來自更高組件的物件陣列傳遞的)
在這一點上,我不確定我是否錯誤地定義了我的道具型別,或者我的設定方式是否存在另一個問題。任何有關配置我的專案以便可以匯入 .tsx 檔案或正確定義我的道具型別的幫助將不勝感激!
這是我的 tsconfig.json 檔案
{
"compilerOptions": {
"target": "es2016",
"module": "esnext",
"noImplicitAny": true,
"esModuleInterop": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"strict": true,
"jsx": "react-jsx",
"allowJs": true,
"checkJs": false,
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"include": [
"src"
]
}
uj5u.com熱心網友回復:
評論中共享的控制臺日志解釋了這個問題。products記錄為:
{products: Array(20), loading: false}
.find()存在于Array.prototype,但正在物件上呼叫。propproducts應該作為產品陣列傳遞,而不是一個物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/369883.html
下一篇:打字稿私有變數訊息
