简体   繁体   中英

Random Number Choosing On React.js

I am doing a Netflix Clone and I need to change the Banner in every page refresh. I integrated movie details from 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. This array contains movie details. I used Math.random() function and an error came that response is not defined. 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. 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. Instead of the above line,

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

and then later in the.then callback,

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.

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().

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.

response is a block-scoped variable that you're attempting to access.

            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])
                })
            }, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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