首页 > 解决方案 > 使用 .map 浏览列表时不断调用 API 做出反应

问题描述

我已经设置了一个 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 请求,我希望它在第一次获得列表后停止。

我怎样才能做到这一点!

标签: javascriptreactjsapiaxiosstate

解决方案


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

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

推荐阅读