从fetch api对象问题中使用随机返回的项目播放
在我被击中可能的重复标签之前,请听我说。
我有代码
const [value, setValue] = useState();
const [data, setData] = useState();
const handleChange = (e) => {
setValue(e.target.value);
};
const handleClick = () => {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'advanced-movie-search.p.rapidapi.com',
'X-RapidAPI-Key': 'myKeyHere'
}
};
fetch(`https://advanced-movie-search.p.rapidapi.com/discover/movie?
with_genres=${value}&page=18`, options)
.then(response => response.json())
.then(response => {
let res = response
setData(res)
console.log(res)
})
.catch(err => console.error(err));
};
// then returning this here like this.
<div className="card">
<h2>{data?.results?.[Math.floor(Math.random() * data.results.length)].title}</h2>
<p>{data?.results?.[Math.floor(Math.random() * data.results.length)].overview}</p>
</div>
,您可以在这里看到一个API,该API返回20个项目的数组,然后每次单击按钮时随机选择一个API。正如您可以从p标签中分辨出的那样,它运行相同的随机选择,这也将从数组中的20个对象中的任何一个中汲取随机的“概述”。
我要想到的是标题在H2中随机拉出,那么我称之为的所有其他数据将仅来自该对象。
我认为将要接听它的对象并将其保存到一个状态,然后用状态调用。
提前致谢!
Before I'm hit with a possible duplicate tag hear me out.
I have the code
const [value, setValue] = useState();
const [data, setData] = useState();
const handleChange = (e) => {
setValue(e.target.value);
};
const handleClick = () => {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'advanced-movie-search.p.rapidapi.com',
'X-RapidAPI-Key': 'myKeyHere'
}
};
fetch(`https://advanced-movie-search.p.rapidapi.com/discover/movie?
with_genres=${value}&page=18`, options)
.then(response => response.json())
.then(response => {
let res = response
setData(res)
console.log(res)
})
.catch(err => console.error(err));
};
// then returning this here like this.
<div className="card">
<h2>{data?.results?.[Math.floor(Math.random() * data.results.length)].title}</h2>
<p>{data?.results?.[Math.floor(Math.random() * data.results.length)].overview}</p>
</div>
as you can see here I'm calling an api which returns an array of 20 items then randomly selecting one every time the button is clicked. as you can probably tell from the p tag which is running the same random selection this too will pull a random "overview" from any of the 20 objects from the array.
What I'm trying to is once the title is pulled randomly in the h2 then all other data I call will come from only that object.
What I thought would would is to take the object that gets called and save it to a state then call it with state.overview or whatever I have no idea if that will work or how to even do it though.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我的解决方案:
currentresult
currentResult
使用setCurrentResult
data?results?[currentResult] ...
Here is my solution:
currentResult
currentResult
usingsetCurrentResult
data?.results?[currentResult]...