英文:
Getting TypeError: Cannot read properties of undefined (reading 'map') when i try to fetch data
问题
我有一个React前端,当我尝试从我的Node.js后端获取数据时,但我的API似乎没有问题。
const SingleProductPage = () => {
const { productId } = useParams();
const [product, setProduct] = useState({});
useEffect(() => {
const fetchProduct = async () => {
const { data } = await axios.get(`/api/Product/${productId}`);
setProduct(data);
};
fetchProduct();
}, [productId]);
if (!product) {
return <Error errorMessage="抱歉,未找到产品!" />;
}
return (
<div className="single-slider-div">
<Splide>
{product.src.map((src, index) => (
<SplideSlide>
<img key={index} src={src} alt="产品图片" />
</SplideSlide>
))}
</Splide>
</div>
);
};
export default SingleProductPage;
我尝试将一个对象设置为product的初始状态,但返回了相同的错误,我尝试测试后端路由,它运行正常。我已添加了相关部分的代码。
英文:
I have a react frontend and when i try to get data from my node js backend but my api seems to be in order
const SingleProductPage = () => {
const { productId } = useParams();
const [product, setProduct] = useState({});
useEffect(() => {
const fetchProduct = async () => {
const { data } = await axios.get(`/api/Product/${productId}`);
setProduct(data);
};
fetchProduct();
}, [productId]);
if (!product) {
return <Error errorMessage="Sorry, Product not found!" />;
}
return (
<div className="single-slider-div">
<Splide>
{product.src.map((src, index) => (
<SplideSlide>
<img key={index} src={src} alt="product img" />
</SplideSlide>
))}
</Splide>
</div>
);
};
export default SingleProductPage;
I tried setting an object as the initial state for product but it returns the same error, i tried testing the backend route and it works fine. I have added relevant parts of the code.
答案1
得分: 1
在你的返回语句中添加对 product
和 product.src
的条件检查。还要在 SplideSlide
组件上添加 key={index}
。
return (
<div className="single-slider-div">
<Splide>
{product && product.src && product.src.map((src, index) => (
<SplideSlide key={index}>
<img src={src} alt="product img" />
</SplideSlide>
))}
</Splide>
</div>
);
英文:
Add a conditional check for product
and product.src
in your return statement. Also add key={index}
to the SplideSlide
component.
return (
<div className="single-slider-div">
<Splide>
{product && product.src && product.src.map((src, index) => (
<SplideSlide key={index}>
<img src={src} alt="product img" />
</SplideSlide>
))}
</Splide>
</div>
);
答案2
得分: 0
代码已翻译如下:
似乎您正尝试在组件呈现之前访问product.src,因此出现了未定义的值错误。您可以将代码重构如下 -
```jsx
const SingleProductPage = () => {
const { productId } = useParams();
const [product, setProduct] = useState({});
useEffect(() => {
const fetchProduct = async () => {
try {
const { data } = await axios.get(`/api/Product/${productId}`);
setProduct(data);
} catch (error) {
//? 错误处理
console.log(error);
}
};
fetchProduct();
}, [productId]);
// 将if语句更改以考虑product.src
if (!product || !product.src) {
return <Error errorMessage="抱歉,找不到产品!" />;
}
return (
<div className="single-slider-div">
<Splide>
{product.src.map((src, index) => (
// 在此定义key属性
<SplideSlide key={index}>
<img src={src} alt="product" />
</SplideSlide>
))}
</Splide>
</div>
);
};
export default SingleProductPage;
此外,我还将key属性移到"SplideSlide"组件上,因为在映射数组时,按照React文档中这里提到的最佳实践,最好在最外层元素上定义key属性。
<details>
<summary>英文:</summary>
It seems like you are trying to access the product.src before the component is rendered and hence the undefined value error. You can refactor the code as follows ->
const SingleProductPage = () => {
const { productId } = useParams();
const [product, setProduct] = useState({});
useEffect(() => {
const fetchProduct = async () => {
try {
const { data } = await axios.get(/api/Product/${productId}
);
setProduct(data);
} catch (error) {
//? Error handling
console.log(error);
}
};
fetchProduct();
}, [productId]);
// changed the if statement to factor in the product.src
if (!product || !product.src) {
return <Error errorMessage="Sorry, Product not found!" />;
}
return (
<div className="single-slider-div">
<Splide>
{product.src.map((src, index) => (
// defining key prop here
<SplideSlide key={index}>
<img src={src} alt="product" />
</SplideSlide>
))}
</Splide>
</div>
);
};
export default SingleProductPage;
In addition, I also moved the key prop up to the "SplideSlide" component as it is best practice to define the key prop at the outermost element when mapping over an array as mentioned [here][1] in React docs.
[1]: https://legacy.reactjs.org/docs/lists-and-keys.html
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论