[英]Random Number Choosing On React.js
我正在做一个 Netflix 克隆,我需要在每次页面刷新时更改横幅。 我整合了来自 TMDb 的电影细节。 所以我想选择一个介于 0 到 19 之间的随机数。我需要该随机数通过数组中的数字在横幅上显示电影。 此数组包含电影详细信息。 我使用Math.random()
function 并出现错误,即未定义response
。 我该如何解决这个问题。 请帮我。
这是我的代码:
import React, { useState } from 'react' import './Banner.css' import {useEffect} from 'react' import {API_KEY,imageUrl} from '../../Constants/Constants' import axios from '../../Axios' function Banner() { const [movie, setMovie] = useState() const results = response.data.results const newIndex = Math.floor(Math.rand() * results.length) useEffect(() => { axios.get(`trending/all/week?api_key=${API_KEY}&language=en-US`).then((response)=>{ console.log(response.data); setMovie(response.data.results[newIndex]) }) }, []) return ( <div className="banner" style={{backgroundImage:`url(${movie? imageUrl+movie.backdrop_path: ""})`}}> <div className="content"> <h1 className="title">{movie? movie.title: ""}</h1> <div className="banner-buttons"> <button className="button">Play</button> <button className="button">My List</button> </div> <h1 className="description">{movie? movie.overview: ""}</h1> </div> <div className="fade-bottom"></div> </div> ) } export default Banner
const results = response.data.results
这一行,显然会抛出一个错误,因为在执行的这一点上,没有定义响应。 您稍后只能在axios.get().then()
回调中获得它。 你想在那里设置结果,但使用变量是行不通的。 您希望此结果在渲染中保持不变,因此将结果存储在 state 中,而不是常量。 而不是上面的行,
const [results, setResults] = useState(null);
然后在.then 回调中,
setResults(response.data.results);
为您的电影指定一个初始占位符值,可能是加载 animation,直到您从 axios 调用中获得响应。
还,
setMovie(response.data.results[newIndex])
将上述内容放入您的 useEffect 将导致在安装时仅设置一次电影,因为具有空依赖数组的 useEffect 挂钩用作 ComponentDidMount()。
如果您想随机循环获取的电影,请考虑使用 setInterval 并使用Math.random()
生成一个新的随机索引(不是问题代码片段中使用的Math.rand()
),然后渲染结果指数。
response 是您尝试访问的块范围变量。
const [movie, setMovie] = useState()
useEffect(() => {
axios.get(`trending/all/week?api_key=${API_KEY}&language=en-US`).then((response)=>{
const newIndex = Math.floor(Math.rand() * response.data.results.length + 1)
setMovie(response.data.results[newIndex])
})
}, [])
或者
const [movie, setMovie] = useState()
const generateRandomNum = (max) => {
Math.floor(Math.rand() * max + 1)
}
useEffect(() => {
axios.get(`trending/all/week?api_key=${API_KEY}&language=en-US`).then((response)=>{
const newIndex = generateRandomNum(response.data.results)
setMovie(response.data.results[newIndex])
})
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.