[英]object.js with state in react ( Cannot read property 'map' of undefined)
I am using js Object and in this object I have 3 section of data: first section (New Arrival) second section (Best Seller) and third section (Special Offer), when I use array.map() to loop the data this error happen我正在使用 js Object 并且在这个 object 中我有 3 部分数据:第一部分(新品)第二部分(畅销书)和第三部分(特价商品),当我使用 array.map() 循环数据时出现此错误发生
I saw many problems here like mine but no solution be right with me我在这里看到了很多像我一样的问题,但没有适合我的解决方案
and this is the code这是代码
import ProductItem from './ProductItem';
import {getAll} from '../../api/product';
class Products extends Component {
state ={
products :[]
};
componentDidMount(){
getAll().then(data =>{
this.setState({
products :data
})
});
}
render() {
return (
<div className="container">
<div className="head-with-border"><h2>New Arrival</h2></div>
<div className="products">
{this.state.products.bestSeller.map(product =>
<div className={"product"} key={product.id}>
<ProductItem product={product}/>
</div>
)}
</div>
</div>
)
}
}
export default Products;
You have a race condtion in your code.您的代码中存在竞争条件。 The initial render happens befor you upload the data with fetch.
初始渲染发生在您使用 fetch 上传数据之前。
import ProductItem from './ProductItem';
import {getAll} from '../../api/product';
class Products extends Component {
state ={
products :[]
};
componentDidMount(){
fetchData()
}
const fetchData = async () => {
let data = await getAll()
this.setState({
products :data
})
}
render() {
return (
<div className="container">
<div className="head-with-border"><h2>New Arrival</h2></div>
<div className="products">
{(this.state.products.bestSeller
? this.state.products.bestSeller
: []
).map(product =>
<div className={"product"} key={product.id}>
<ProductItem product={product}/>
</div>
)}
</div>
</div>
)
}
}
export default Products;
You need to check for the default empty state:您需要检查默认的空 state:
import ProductItem from './ProductItem';
import {getAll} from '../../api/product';
class Products extends Component {
state ={
products: {}
};
componentDidMount(){
getAll().then(data =>{
this.setState({
products :data
})
});
}
render() {
const { bestSeller } = this.state.products;
return (
<div className="container">
<div className="head-with-border"><h2>New Arrival</h2></div>
<div className="products">
{bestSeller && bestSeller.map(product =>
<div className={"product"} key={product.id}>
<ProductItem product={product}/>
</div>
)}
</div>
</div>
)
}
}
export default Products;
I also changed your default product state to an empty object instead of a array to align it with the data structure you are working with.我还将您的默认产品 state 更改为空的 object 而不是数组,以使其与您正在使用的数据结构对齐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.