简体   繁体   English

在 React 中渲染组件时,如何使用一个 axios 请求的 output 作为另一个请求的依赖项?

[英]How do I use the output of one axios request as a dependency for another when rendering components in React?

I have been struggling with this for some time and I am not sure how to solve the issue.我已经为此苦苦挣扎了一段时间,我不确定如何解决这个问题。

Basically, I am trying to render some components onto my Index page, this is my code below:基本上,我试图将一些组件呈现到我的索引页面上,这是我的代码如下:

App.js

import Index from "./Components/Index"
import axios from "axios"

export default function App() {
    const [movieList, setMovieList] = React.useState([])
    let featured = []
    let coming = []
    let showing = []

    React.useEffect(() => {
        console.log("Ran App Effects")
        axios.get(`API_CALL_TO_GET_LIST_OF_MOVIES`)
        .then(res =>{
            setMovieList(res.data)
        })
    }, [])

 
    return(
        <div>
             {movieList.map(movie =>{
            if(movie.status === 'featured'){
                featured.push(movie.api_ID)
            } else if (movie.status === 'upcoming'){
                coming.push(movie.api_ID)
            } else{
                showing.push(movie.api_ID)
            }
            })}
        
        <Index featured={featured} coming={coming} showing={showing}/>
        </div>
        
           
    )
}

In the code above I am receiving an array of Objects and based on what is in their status I am putting them in some empty arrays and sending them as props into my Index component.在上面的代码中,我收到了一个对象数组,根据它们的状态,我将它们放入一些空的 arrays 中,并将它们作为 props 发送到我的 Index 组件中。 This is what my index component looks like:这是我的索引组件的样子:

import React from "react"
import Header from "./Header"
import Footer from "./Footer"
import MovieCard from "./MovieCard"
import axios from "axios"

export default function Index(props) {
    const [featuredMovies, setFeaturedMovies] = React.useState([])
    const [comingMovies, setComingMovies] = React.useState([])
    //const featured = [419704,338762,495764,38700,454626,475557]
    //const coming = [400160,514847,556678,508439,524047,572751]
    


    React.useEffect(() => {
        console.log("Ran Effect")

        axios.all(props.featured.map(l => axios.get(`API_CALL_TO_GET_SPECIFIC_MOVIE/${l}`)))
        .then(axios.spread(function (...res){
            setFeaturedMovies(res)
        }))
        .catch((err) => console.log(err))

        axios.all(props.coming.map(l => axios.get(`API_CALL_TO_GET_SPECIFIC_MOVIE/${l}`)))
        .then(axios.spread(function (...res){
            setComingMovies(res)
        }))
        .catch((err) => console.log(err))

    }, []) 


    return(
        <body>
            <Header />
            <section className="home">
                <div className="container">
                    <div className="row">
                        <div className="col-12">
                            <a className="home__title">FEATURED MOVIES</a>
                        </div>
                        
                        { featuredMovies.map(movie =>{
                return <MovieCard movie={movie} featured={true} />
                        }) }
                        {console.log(props.featured)}

                    </div>     
                </div>
            </section>


            <section className="home">
                <div className="container">
                    <div className="row">
                        <div className="col-12">
                            <a className="home__title">COMING SOON</a>
                        </div>
                        { comingMovies.map(movie =>{
                return <MovieCard movie={movie} featured={false} />
                        })}
                    </div>      
                </div>
            </section>
            
            <Footer/>
        </body>
    )
}

The issue I am running into is, whenever I run the app for the first time it works fine but then when I hit the refresh button the components do not render anymore我遇到的问题是,每当我第一次运行该应用程序时,它都可以正常工作,但是当我点击刷新按钮时,组件不再呈现

The only time it re-renders when I refresh the page is when I uncomment,当我刷新页面时,它唯一一次重新呈现是在我取消注释时,

//const featured = [419704,338762,495764,38700,454626,475557]
//const coming = [400160,514847,556678,508439,524047,572751]

and replace the props.featured.map and props.coming.map with featured.map and coming.map hence using the hard coded values and not the values passed in from the props.并将props.featured.mapprops.coming.map替换为featured.mapcoming.map ,因此使用硬编码值而不是从道具传入的值。

Any help with this would be much appreciated as I am completely stuck and currently pulling my hair out.任何对此的帮助将不胜感激,因为我完全被卡住了,目前正在拔头发。

I took the liberty to tinker with your code.我冒昧地修改了你的代码。 In the example below I've rearranged the data into three sets with the help of useMemo and by checking the status property of each movie.在下面的示例中,我在useMemo的帮助下并通过检查每部电影的状态属性将数据重新排列为三组。 It is important to keep any data related logic outside of the render logic.将任何与数据相关的逻辑保留在渲染逻辑之外很重要。

I also moved around some of your HTML structure.我还移动了您的一些 HTML 结构。 You were outputting a <body> tag inside of a <div> .您在<div>中输出了一个<body>标签。 The outer layer should be in control of the outer HTML structure, so I moved that HTML to the App component.外层应该控制外部 HTML 结构,所以我将 HTML 移动到App组件。

import { useState, useEffect, useMemo } from 'react'
import Header from "./Components/Header"
import Footer from "./Components/Footer"
import Index from "./Components/Index"
import axios from "axios"

export default function App() {
  const [movieList, setMovieList] = useState([])

  const featuredMovies = useMemo(() => {
    return movieList.filter(({ status }) => status === 'featured');
  }, [movieList]);

  const upcomingMovies = useMemo(() => {
    return movieList.filter(({ status }) => status === 'upcoming');
  }, [movieList]);

  const showingMovies = useMemo(() => {
    return movieList.filter(({ status }) => status !== 'featured' && status !== 'upcoming');
  }, [movieList]);

  useEffect(() => {
    axios.get(`API_CALL_TO_GET_LIST_OF_MOVIES`)
      .then(res =>{
        setMovieList(res.data)
      })
  }, [])

  return (
    <body>
      <Header />

      <Index data={featuredMovies} title="Featured Movies" featured={true} />
      <Index data={upcomingMovies} title="Coming Soon" />
      <Index data={showingMovies} title="Showing Now" />

      <Footer/>
    </body>     
  )
}

Since we now have three sets of movies (featured, upcoming, and playing) it would also make sense to have three components that handle those data sets instead of having one that handles multiple.由于我们现在有三组电影(精选、即将上映和正在播放),因此使用三个组件来处理这些数据集而不是让一个组件处理多个数据集也很有意义。 Each Index component gets its own data set and other props to render the movies within it.每个Index组件都有自己的数据集和其他道具来渲染其中的电影。

import MovieCard from "./MovieCard"

export default function Index({ data, title, featured = false }) {
  return (
    <section className="home">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <a className="home__title">{title}</a>
          </div>
          
          {data.map(movie => {
            return <MovieCard movie={movie} featured={featured} />
          })}
        </div>     
      </div>
    </section>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我使用 React 和 Axios 进行 API 请求时“无法获取” - "Cannot get" when I do API request with React and Axios 如何在 React 中隐藏和显示带有 useState 或条件渲染的组件? - How do I hide and show components with useState or conditional rendering in React? 在React中,如何使用条件渲染? - In React how do I use a conditional with rendering? 如何在反应中使用 axios 发出 POST 请求? - How do I make a POST request using axios in react? 在呈现我的反应组件之前,如何让 axios 获取请求等待 - How can I make an axios get request wait before rendering my react component 如何在与组合组件的反应中进行条件渲染 - How to do conditional rendering in react with combining components 反应如何使用 setInterval 与 useEfecct 和 axios 请求 - React how to use setInterval with useEfecct and axios request 在 React 中,当我在另一个组件中触发 Add 函数时,如何正确使用钩子来更新一个组件? - In React, how do I properly use hooks to update one component when I trigger an Add function in another component? 如何使用React和Axios将this.data传递给其他组件 - How do I pass this.data through to other components with React and Axios 反应:使用 Axios 所以我可以在我的第二个请求中使用我的第一个请求中的数据 - React: Using Axios so I can use data from my first request in my second one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM