Blockquote
大家好,我是React_hooks的新手,我正尝试在组件中获取项目,但是却收到错误消息“无法读取未定义的属性'something'”,因为该组件在分派该组件之前返回了jsx。函数getItem(id),当我在返回部分不输入任何内容时,我会获取该项目的信息
import React, { Component,useEffect, useState } from 'react';
import {getItem, addComment,addReply, addItem, deleteItem } from '../actions/itemActions';
import {addToCart} from '../actions/authActions';
import { CustomInput, Col, Row, Container, ListGroup, ListGroupItem, Button, Form, FormGroup, Label, Input, Alert } from 'reactstrap';
import ReactTimeAgo from 'react-time-ago';
import { useDispatch,useSelector } from 'react-redux';
import {Link} from 'react-router-dom';function Item(props) {
const dispatch = useDispatch();
const id = props.match.params.id;
const [item, setItem] = useState({})
useEffect(() => {
dispatch(getItem(id)).then(() => setItem(product))
}, [id]);
const img1 = "http://localhost:5000/"
const product = useSelector(state => state.item.product)
const isAuthenticated = useSelector(state => state.auth.isAuthenticated)
console.log(item)
return (
<div>
{isAuthenticated ? (
<ListGroupItem className="m-2">
{item.images.length == 0 ? <img className="img_item" src="https://via.placeholder.com/300x300/FFFFFF/000000/?text=goshop.com" />:null}
{item.images.map((image) => (
<div>
<img className="img_item" src={img1,image} />
</div>
))}<div>
<Link to={{
pathname:`/item/${item._id}`,
query:{item: item}
}}>{item.name}</Link>
</div>
<div>
<span className='text-danger mr-3'> Price: {item.price}$ </span>
{item.price_sale ? <span className='last_price'> {item.price_sale}$ </span>:null }
</div>
</ListGroupItem>
):null}
</div>
);
}export default Item;