Arrays 使用ID'对电影数据库进行多次调用;存储在localstorage中的
我正在使用React中的moviedatabase API创建一个站点。() 我创建了一个按钮,用户可以单击该按钮将他们正在观看的电影的id添加到存储在localstorage中的电影id数组中 在“观看”页面上,我可以使用此代码通过说明索引号movies[0]从数组中获取1部电影的信息,但我希望映射/for循环本地存储中存储的所有ID。我该怎么做Arrays 使用ID'对电影数据库进行多次调用;存储在localstorage中的,arrays,reactjs,local-storage,Arrays,Reactjs,Local Storage,我正在使用React中的moviedatabase API创建一个站点。() 我创建了一个按钮,用户可以单击该按钮将他们正在观看的电影的id添加到存储在localstorage中的电影id数组中 在“观看”页面上,我可以使用此代码通过说明索引号movies[0]从数组中获取1部电影的信息,但我希望映射/for循环本地存储中存储的所有ID。我该怎么做 import React, { useState, useEffect } from 'react' import Axios from '
import React, { useState, useEffect } from 'react'
import Axios from 'axios'
import Moviedetails from './Moviedetails'
const Watchlist = () => {
const [isloading, setIsloading] = useState(true)
const [towatch, setTowatch] = useState()
const [moviedetails, setMoviedetails] = useState()
useEffect(() => {
const fetchitems = async () => {
const movies = JSON.parse(localStorage.getItem("movies"))
setTowatch(movies)
const result = await Axios(`https://api.themoviedb.org/3/movie/${movies[0]}?api_key=(API KEY GOES HERE)`)
setMoviedetails(result.data)
setIsloading(false)
}
fetchitems()
},[isloading])
return (
<div>
</div>
)
}
export default Watchlist
import React,{useState,useffect}来自“React”
从“Axios”导入Axios
从“/Moviedetails”导入电影详细信息
常量监视列表=()=>{
常量[isloading,setIsloading]=useState(真)
const[towatch,setTowatch]=useState()
const[moviedetails,setMoviedetails]=useState()
useffect(()=>{
const fetchitems=async()=>{
const movies=JSON.parse(localStorage.getItem(“movies”))
setTowatch(电影)
常量结果=等待Axios(`https://api.themoviedb.org/3/movie/${movies[0]}?api_key=(api key在这里)`)
setMoviedetails(result.data)
setIsloading(错误)
}
fetchitems()
},[isloading])
返回(
)
}
导出默认观察列表
如果要进行并行api调用,请使用Promise.all
。所以
const movies = JSON.parse(localStorage.getItem("movies"))
// movies.map creates an array of promises and
// Promise.all resolves them all into an array of results
const results =
Promise.all(movies.map(id => Axios(`your-url`))
.then(results => {
// do something with the results
}
)
公平警告,使用数量不确定的api调用执行此操作可能会导致性能下降。您应该检查是否可以将多个id传递给一个api调用。非常感谢您。我有一个google,现在看起来你不能将多个id传递给一个api调用,但是你的代码解决了我的问题,并让它以我想要的方式工作。