[英]I got the error "TypeError: products.map is not a function"
This error is appears in the Home page of the website.此错误出现在网站的主页中。 When I'm in another page and click the back button to open the Home Page this error appears.
当我在另一个页面并单击后退按钮打开主页时,会出现此错误。 But when I'm refreshing the Home page, this error despairs.
但是当我刷新主页时,这个错误令人绝望。 This is the Code that I used in home page
这是我在主页中使用的代码
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom'
import axios from 'axios';
import { useSelector, useDispatch } from 'react-redux';
import { listProducts } from '../actions/productActions';
function HomeScreen(props) {
const productList = useSelector(state => state.productList);
const { products, loading, error } = productList;
const dispatch = useDispatch();
useEffect(() => {
dispatch(listProducts());
return () =>{
//
};
}, [])
return loading ? <div>Loading...</div> :
error ? <div>{error}</div> :
<ul className="products">
{
products.map(product =>
<li key={product._id}>
<div className="product">
<Link to={'/product/' + product._id}>
<img className="products-image" src={product.image} alt="product"/>
</Link>
<div className="product-name">
<Link to= {'/product/' + product._id}> {product.name} </Link>
</div>
<div className="product-brand">{product.brand}</div>
<div className="product-price">Rs.{product.price}</div>
<div className="product-rating">{product.rating} Stars ({product.numReivews}Reviews)</div>
</div>
</li>)
}
</ul>
}
export default HomeScreen;
The main reason behind is .map()
can be used only on arrays. You can use null
or undefined
checks before using .map()
as:背后的主要原因是
.map()
只能在 arrays 上使用。您可以在使用.map()
之前使用null
或undefined
检查:
<ul className="products">
{
products && products.map(product =>
<li key={product._id}>
{ /* rest of the code */ }
</li>)
}
</ul>
+1 suggestion: +1 建议:
Also it is worth to check the type of productList
is in the store, maybe initially it's an empty object. Although clearly it has to be an array to iterate through on it with .map()
.同样值得检查商店中
productList
的类型,也许最初它是一个空的 object。尽管很明显它必须是一个数组才能使用.map()
对其进行迭代。 Thus I would use an empty array as []
or null
.因此,我会使用一个空数组作为
[]
或null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.