简体   繁体   English

ReactJS,新的 axios 在组件的每次渲染时调用

[英]ReactJS, new axios call at every render of the component

I'm trying to dynamically render some components mapping an array of objects from an API call.我正在尝试动态渲染一些组件,这些组件映射来自 API 调用的对象数组。 I can't wrap my head around the syntax of this one.我无法理解这个语法。

I have to fetch from this url:我必须从这个 url 中获取:

https://fakestoreapi.com/products

And for each object in the array I have to render Product.js inside ProductContainer.js.对于数组中的每个 object,我必须在 ProductContainer.js 中渲染 Product.js。

ProductContainer.js:产品容器.js:

import axios from "axios";
import React, { useState, useEffect } from "react";
import "../styles/ProductContainer.scss";
import Product from "./Product";

const ProductContainer = () => {
  const [productArray, setProductArray] = useState("");
  const [imgUrl, setImgUrl] = useState("");
  const [nameUrl, setNameUrl] = useState("");
  const [priceUrl, setPriceUrl] = useState("");

  useEffect(() => {
    axios.get("https://fakestoreapi.com/products").then((res) => {
      setProductArray(res.data);
      setImgUrl(res.data.image);
      setNameUrl(res.data.title);
      setPriceUrl(res.data.price);
    });
  }, []);

  return (
    <div className="product-container">
      {productArray.map((e) => {
        <Product imgUrl={imgUrl} nameUrl={nameUrl} priceUrl={priceUrl} />;
      })}
    </div>
  );
};

export default ProductContainer;

Thank you!谢谢!

The image , title and price are properties of each product, not of the whole response from the API. imagetitleprice是每个产品的属性,而不是来自 API 的全部响应。

Also productArray should be initialized to an array and not a string. productArray也应该初始化为数组而不是字符串。

So所以

import axios from "axios";
import React, { useState, useEffect } from "react";
import "../styles/ProductContainer.scss";
import Product from "./Product";

const ProductContainer = () => {
  const [productArray, setProductArray] = useState([]);

  useEffect(() => {
    axios.get("https://fakestoreapi.com/products").then((res) => {
      setProductArray(res.data);
    });
  }, []);

  return (
    <div className="product-container">
      {productArray.map((product) => {
        <Product imgUrl={product.image} name={product.name} price={product.price} />;
      })}
    </div>
  );
};

export default ProductContainer;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM