英文:
Receiving data from API in console log but can't able to show them on the web page
问题
# 通过REST API和AXIOS获取产品详细信息,数据已在控制台记录,但无法在单个产品页面显示数据
# 请帮我解决这个错误
# 这是我的单个产品页面
import { Add, Remove } from '@mui/icons-material';
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import styled from 'styled-components';
import Announcement from '../components/Announcement';
import Footer from '../components/Footer';
import Navbar from '../components/navbar';
import Newsletter from '../components/Newsletter';
import { mobile } from '../Responsive';
import { publicRequest } from '../requestMethods';
const Container = styled.div```
# 这是我的AXIOS请求方法
import axios from "axios";
const BASE_URL = "http://localhost:5000/api/";
const TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzZjdiNTk5OTliYjNkMzI2MGU4ZGY0NSIsImlzQWRtaW4iOnRydWUsImlhdCI6MTY3ODQzNzI5NywiZXhwIjoxNjc4Njk2NDk3fQ.4ncPTwHxOPKHxjK3m8LgmN04NzdfBWtvKiLoce6b20Q";
export const publicRequest = axios.create({
baseURL: BASE_URL,
});
export const userRequest = axios.create({
baseURL: BASE_URL,
headers: { token: Bearer ${TOKEN}
}
})
[这是我的控制台日志,其中我收到了数据](https://i.stack.imgur.com/ovIax.png)
<details>
<summary>英文:</summary>
# I'm fetching product details by using REST API and AXIOS I'm receiving the data in my console log but can't able to show the data in the single product page where i want to show
# please help me to solve this error
# this is my single product page
import { Add, Remove } from '@mui/icons-material';
import React, { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom';
import styled from 'styled-components'
import Announcement from '../components/Announcement';
import Footer from '../components/Footer';
import Navbar from '../components/navbar';
import Newsletter from '../components/Newsletter';
import { mobile } from '../Responsive';
import { publicRequest } from '../requestMethods';
// import { addProduct } from '../redux/cartRedux';
// import { useDispatch } from 'react-redux';
const Container = styled.div``;
const Wrapper = styled.div
;
padding: 50px;
display: flex;
${mobile({padding: "10px", flexDirection:"column"})}
const ImgContainer = styled.div
;
flex: 1;
const Image = styled.img
;
width: 100%;
height: 90vh;
object-fit: cover;
${mobile({height: "40vh"})}
const InfoContainer = styled.div
;
flex: 1;
padding: 0 50px;
${mobile({padding: "10px"})}
const Title = styled.h1
;
font-weight: 200;
const Desc = styled.p
;
margin: 20px 0;
const Price = styled.span
;
font-size: 40px;
font-weight: 100;
const FilterContainer = styled.div
;
width: 50%;
display: flex;
justify-content: space-between;
margin: 30px 0;
${mobile({width: "100%"})}
const Filter = styled.div
;
display: flex;
align-items: center;
const FilterTitle = styled.span
;
font-size: 28px;
font-weight: 20;
const FilterColor = styled.div
;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: ${props=>props.color};
margin: 0 5px;
cursor: pointer;
const FilterSize = styled.select`
margin-left: 10px;
padding: 5px;
`;
const FilterSizeOption = styled.option``;
const AddContainer = styled.div
;
width: 50%;
display: flex;
align-items: center;
justify-content: space-between;
${mobile({width: "100%"})}
const AmountContainer = styled.div
;
display: flex;
align-items: center;
font-weight: 700;
const Amount = styled.span
;
width: 30px;
height: 30px;
border-radius: 10px;
border: 1px solid teal;
display: flex;
justify-content: center;
align-items: center;
margin: 0 5px;
const Button = styled.button`
padding: 15px;
border: 2px solid teal;
background-color: white;
cursor: pointer;
font-weight: 500;
&:hover{
background-color: #f8f4f4;
}
`;
const Product = () => {
const location = useLocation();
const id = location.pathname.split("/")[2];
const [product, setProduct] = useState({});
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("/products/find/" + id);
setProduct(res.data);
console.log(res);
} catch(error) {
console.log(error);
}
};
getProduct();
}, [id]);
return (
<Container>
<Navbar/>
<Announcement/>
<Wrapper>
<ImgContainer>
<Image src= {product.img} />
</ImgContainer>
<InfoContainer>
<Title>{product.title}
</Title>
<Desc>{product.desc}</Desc>
<Price>{product.price}</Price>
<FilterContainer>
<Filter>
<FilterTitle>Color</FilterTitle>
<FilterColor color="black" />
<FilterColor color="darkblue"/>
<FilterColor color="gray"/>
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize>
<FilterSizeOption>XS</FilterSizeOption>
<FilterSizeOption>S</FilterSizeOption>
<FilterSizeOption>M</FilterSizeOption>
<FilterSizeOption>L</FilterSizeOption>
<FilterSizeOption>XL</FilterSizeOption>
<FilterSizeOption>XXL</FilterSizeOption>
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove/>
<Amount>1</Amount>
<Add/>
</AmountContainer>
<Button>Add to cart</Button>
</AddContainer>
</InfoContainer>
</Wrapper>
<Newsletter/>
<Footer/>
</Container>
)
}
export default Product
# and this is my AXIOS request method
import axios from "axios";
const BASE_URL = "http://localhost:5000/api/";
const TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzZjdiNTk5OTliYjNkMzI2MGU4ZGY0NSIsImlzQWRtaW4iOnRydWUsImlhdCI6MTY3ODQzNzI5NywiZXhwIjoxNjc4Njk2NDk3fQ.4ncPTwHxOPKHxjK3m8LgmN04NzdfBWtvKiLoce6b20Q";
export const publicRequest = axios.create({
baseURL: BASE_URL,
});
export const userRequest = axios.create({
baseURL: BASE_URL,
header: {token: Bearer ${TOKEN}
}
})
[This is my console log where i received the data](https://i.stack.imgur.com/ovIax.png)
</details>
# 答案1
**得分**: 0
以下的代码或许对你有帮助:
```jsx
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("/products/find/" + id);
setProduct(res?.data?.product?.categories);
console.log(res);
} catch(error) {
console.log(error);
}
};
getProduct();
}, [id]);
// 下面是另外的变化:
product?.map((singleproduct) => (
<ImgContainer>
<Image src={singleproduct.img} />
</ImgContainer>
<InfoContainer>
<Title>{singleproduct.title}</Title>
<Desc>{singleproduct.desc}</Desc>
<Price>{singleproduct.price}</Price>
<FilterContainer>
<Filter>
<FilterTitle>Color</FilterTitle>
<FilterColor color="black" />
<FilterColor color="darkblue" />
<FilterColor color="gray" />
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize>
<FilterSizeOption>XS</FilterSizeOption>
<FilterSizeOption>S</FilterSizeOption>
<FilterSizeOption>M</FilterSizeOption>
<FilterSizeOption>L</FilterSizeOption>
<FilterSizeOption>XL</FilterSizeOption>
<FilterSizeOption>XXL</FilterSizeOption>
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove/>
<Amount>1</Amount>
<Add/>
</AmountContainer>
<Button>Add to cart</Button>
</AddContainer>
</InfoContainer>
))
英文:
following code might help you :
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("/products/find/" + id);
setProduct(res?.data?.product?.categories);
console.log(res);
} catch(error) {
console.log(error);
}
};
getProduct();
}, [id]);
another changes below :
product?.map((singleproduct)=>(
<ImgContainer>
<Image src= {singleproduct.img} />
</ImgContainer>
<InfoContainer>
<Title>{singleproduct.title}
</Title>
<Desc>{singleproduct.desc}</Desc>
<Price>{singleproduct.price}</Price>
<FilterContainer>
<Filter>
<FilterTitle>Color</FilterTitle>
<FilterColor color="black" />
<FilterColor color="darkblue"/>
<FilterColor color="gray"/>
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize>
<FilterSizeOption>XS</FilterSizeOption>
<FilterSizeOption>S</FilterSizeOption>
<FilterSizeOption>M</FilterSizeOption>
<FilterSizeOption>L</FilterSizeOption>
<FilterSizeOption>XL</FilterSizeOption>
<FilterSizeOption>XXL</FilterSizeOption>
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove/>
<Amount>1</Amount>
<Add/>
</AmountContainer>
<Button>Add to cart</Button>
</AddContainer>
</InfoContainer>)
答案2
得分: 0
你应该将 setProduct(res.data);
修改为 setProduct(res.data.product);
根据你提供的数据截图,结构如下:
{
"data": {
"product": {
...
}
}
}
然而,在useEffect
中调用的 setProduct
函数将整个 data
负载赋给了 product
变量,这是不正确的。
英文:
You should change setProduct(res.data);
to setProduct(res.data.product);
From your screenshot of the data you received, the structure is as following
{
"data": {
"product": {
...
}
}
}
However, the setProduct
function you called in the useEffect
is assigning the entire payload of data
to the product
variable which is incorrect.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论