从 API 中接收数据并记录在控制台,但无法在网页上显示它们。

huangapple go评论84阅读模式
英文:

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&#39;m fetching product details by using REST API and AXIOS I&#39;m receiving the data in my console log but can&#39;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: &quot;10px&quot;, flexDirection:&quot;column&quot;})}
;
const ImgContainer = styled.div
flex: 1;
;
const Image = styled.img
width: 100%;
height: 90vh;
object-fit: cover;
${mobile({height: &quot;40vh&quot;})}
;
const InfoContainer = styled.div
flex: 1;
padding: 0 50px;
${mobile({padding: &quot;10px&quot;})}
;
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: &quot;100%&quot;})}
;
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=&gt;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: &quot;100%&quot;})}
;

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;

&amp;:hover{
    background-color: #f8f4f4;
}

`;

const Product = () => {
const location = useLocation();
const id = location.pathname.split("/")[2];
const [product, setProduct] = useState({});

useEffect(() =&gt; {
  const getProduct = async () =&gt; {
    try {
      const res = await publicRequest.get(&quot;/products/find/&quot; + 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(() =&gt; {
      const getProduct = async () =&gt; {
        try {
          const res = await publicRequest.get(&quot;/products/find/&quot; + id);
          setProduct(res?.data?.product?.categories);
          console.log(res);
        } catch(error) {
            console.log(error);
        }
      };
      getProduct();
    }, [id]);

another changes below :

product?.map((singleproduct)=&gt;(
&lt;ImgContainer&gt;
                &lt;Image src= {singleproduct.img} /&gt;
            &lt;/ImgContainer&gt;
            &lt;InfoContainer&gt;
                &lt;Title&gt;{singleproduct.title}
                &lt;/Title&gt;
                &lt;Desc&gt;{singleproduct.desc}&lt;/Desc&gt;
                &lt;Price&gt;{singleproduct.price}&lt;/Price&gt;
                &lt;FilterContainer&gt;
                    &lt;Filter&gt;
                        &lt;FilterTitle&gt;Color&lt;/FilterTitle&gt;
                        &lt;FilterColor color=&quot;black&quot; /&gt;
                        &lt;FilterColor color=&quot;darkblue&quot;/&gt;
                        &lt;FilterColor color=&quot;gray&quot;/&gt;
                    &lt;/Filter&gt;
                    &lt;Filter&gt;
                        &lt;FilterTitle&gt;Size&lt;/FilterTitle&gt;
                        &lt;FilterSize&gt;
                            &lt;FilterSizeOption&gt;XS&lt;/FilterSizeOption&gt;
                            &lt;FilterSizeOption&gt;S&lt;/FilterSizeOption&gt;
                            &lt;FilterSizeOption&gt;M&lt;/FilterSizeOption&gt;
                            &lt;FilterSizeOption&gt;L&lt;/FilterSizeOption&gt;
                            &lt;FilterSizeOption&gt;XL&lt;/FilterSizeOption&gt;
                            &lt;FilterSizeOption&gt;XXL&lt;/FilterSizeOption&gt;
                        &lt;/FilterSize&gt;
                    &lt;/Filter&gt;
                &lt;/FilterContainer&gt;
                &lt;AddContainer&gt;
                    &lt;AmountContainer&gt;
                        &lt;Remove/&gt;
                        &lt;Amount&gt;1&lt;/Amount&gt;
                        &lt;Add/&gt;
                    &lt;/AmountContainer&gt;
                    &lt;Button&gt;Add to cart&lt;/Button&gt;
                &lt;/AddContainer&gt;
            &lt;/InfoContainer&gt;)

答案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

{
  &quot;data&quot;: {
    &quot;product&quot;: {
      ...
    }
  }
}

However, the setProduct function you called in the useEffect is assigning the entire payload of data to the product variable which is incorrect.

huangapple
  • 本文由 发表于 2023年3月12日 16:24:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定