【问题标题】:react constantly calling the API when using .map to go through the list使用 .map 浏览列表时不断调用 API 做出反应
【发布时间】:2021-10-06 08:46:45
【问题描述】:

我已经设置了一个 Strapi API,并且我正在使用 react 来使用该 API(使用 Axios)。

App.js 中的代码如下所示

import axios from "axios";
import React, {useEffect, useState} from "react";
import LineCard from "./components/Linecard"
function App() {
  
  // don't mind the URL i will fix them later
  const root = "http://localhost:1337"
  const URL = 'http://localhost:1337/pick-up-lines'

  // this is the "messed up" data from strapi
  const [APIdata, setAPIdata] = useState([])

  //this is the clean data
  const [lines, setLines] = useState([])

  // the array that i will be using later to "setLines" state
  const linesFromApi = APIdata.map((line, index) => {
    const profileImage = root + line.users_permissions_user.profilePicture.formats.thumbnail.url
    const userName = line.users_permissions_user.username
    const title = line.title
    const lineBody = line.line
    const rating = line.rating
    const categories = line.categories.map((category, index) => category.categoryName)

    return {
      profileImage,
      userName,
      title,
      lineBody,
      rating,
      categories
    }

  })


  useEffect(() => {
    // calling the API with get method to fetch the data and store it inside APIdata state
    axios.get(URL).then((res) => {
      setAPIdata(res.data)
    })
    setLines(linesFromApi)
  }, [URL, linesFromApi])




  return (
    <div>
     // mapping through the lines list and rendering a card for each element
      {lines.map((line, index) => <LineCard line={line} />)}

    </div >
  );
}

export default App;

我确定这是导致问题的原因

return (
    <div>
      {lines.map((line, index) => <LineCard line={line} />)}

    </div >
  );

我的问题是 react 不断发送 GET 请求,我希望它在第一次获得列表后停止。

我该怎么做!

【问题讨论】:

    标签: javascript reactjs api axios state


    【解决方案1】:

    尝试在您的钩子中添加一个检查,以便在已设置值的情况下限制 api 调用。 像这样的

    useEffect(() => {
     if(lines.length === 0){
      axios.get(URL).then((res) => {
        setAPIdata(res.data)
      })
      setLines(linesFromApi)
     }
    }, [URL, linesFromApi])
    

    【讨论】:

      【解决方案2】:

      您需要将key 属性添加到地图中的元素。

       <div>
            {lines.map((line, index) => <LineCard key={index} line={line} />)}
      </div>
      

      【讨论】:

      • 没有帮助先生!
      猜你喜欢
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 2015-12-25
      • 2017-07-28
      • 2020-02-15
      • 2021-07-29
      • 1970-01-01
      • 2018-08-28
      相关资源
      最近更新 更多