简体   繁体   English

React.js 上的随机数选择

[英]Random Number Choosing On React.js

I am doing a Netflix Clone and I need to change the Banner in every page refresh.我正在做一个 Netflix 克隆,我需要在每次页面刷新时更改横幅。 I integrated movie details from TMDb.我整合了来自 TMDb 的电影细节。 So I want to choose a random number between 0 and 19. I need that random number to display the movie on banner by the number in an array.所以我想选择一个介于 0 到 19 之间的随机数。我需要该随机数通过数组中的数字在横幅上显示电影。 This array contains movie details.此数组包含电影详细信息。 I used Math.random() function and an error came that response is not defined.我使用Math.random() function 并出现错误,即未定义response How Do I solve This.我该如何解决这个问题。 Please Help Me.请帮我。

Here Is My Code:这是我的代码:

 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

This line, will obviously throw an error because at this point in the execution, response is not defined.这一行,显然会抛出一个错误,因为在执行的这一点上,没有定义响应。 You're only getting it later in the axios.get().then() callback.您稍后只能在axios.get().then()回调中获得它。 You'd wanna set results there, but using a variable will not work.你想在那里设置结果,但使用变量是行不通的。 You'd want this result to persist across renders, so store the results in state, not a constant.您希望此结果在渲染中保持不变,因此将结果存储在 state 中,而不是常量。 Instead of the above line,而不是上面的行,

const [results, setResults] = useState(null);

and then later in the.then callback,然后在.then 回调中,

setResults(response.data.results);

Give an initial placeholder value for your movie, maybe a loading animation, till you get the response from the axios call.为您的电影指定一个初始占位符值,可能是加载 animation,直到您从 axios 调用中获得响应。

Also,还,

setMovie(response.data.results[newIndex])

putting the above in your useEffect will result in setting the movie only once,on mount, because the useEffect hook with an empty dependancy array functions as a ComponentDidMount().将上述内容放入您的 useEffect 将导致在安装时仅设置一次电影,因为具有空依赖数组的 useEffect 挂钩用作 ComponentDidMount()。

If you want to randomly loop through the movies fetched, consider using a setInterval and generate a new random index with Math.random() , (not Math.rand() as used in the question code snippet), and render the result at that index.如果您想随机循环获取的电影,请考虑使用 setInterval 并使用Math.random()生成一个新的随机索引(不是问题代码片段中使用的Math.rand() ),然后渲染结果指数。

response is a block-scoped variable that you're attempting to access. 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])
                })
            }, [])

or或者

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM