javascript - 使用 .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 请求,我希望它在第一次获得列表后停止。
我怎样才能做到这一点!
解决方案
尝试在您的钩子中添加一个检查,以便在已设置值的情况下限制 api 调用。像这样的东西
useEffect(() => {
if(lines.length === 0){
axios.get(URL).then((res) => {
setAPIdata(res.data)
})
setLines(linesFromApi)
}
}, [URL, linesFromApi])
推荐阅读
- javascript - D3:数据更新“进入”选择为空
- android - Android Studio 不安装 SDK
- c++ - 如何在 C++ 中使用 libmosquitto 和 SSL/TLS 连接到 mqtt 代理
- html - HTML让html元素只影响div内部
- python - Spark Dataframe 中“float”与“np.nan”的比较
- android - 数据已添加到 Sqlite 但不会显示在 recyclerView
- javascript - 使用 JavaScript 创建 MDL 复选框
- logstash - logstash:文件输入不起作用,标准输出根本不显示任何内容(Windows)
- javascript - 如何在 Typescript 中将 import 语句与 import all 语句结合起来?
- ruby-on-rails - 收藏选择类别和子类别 | 没有按预期工作