【问题标题】:Multiple API Calls in ReactReact 中的多个 API 调用
【发布时间】:2018-12-31 06:13:36
【问题描述】:

我正在制作一个从 API 接收数据的应用。获得这些数据后,我想使用从第一次调用中获得的端点再次调用同一个 API。

fetch(req)
    .then((response)=>(
        response.json()
    )).then((json)=>{
        console.log(json)
        json.meals.map((obj)=>{
            let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
            let req = new Request(url,{
            method: 'GET',
            headers: header
        })
        fetch(req)
        .then((response)=>(
        response.json()
        )).then((json)=>{
            console.log(json);
        this.setState((prevState)=>{
                recipe: prevState.recipe.push(json)
        })
        })
        })
        this.setState(()=>{
            return{
                data: json
            }
        })
    })

我在这里发出了两个获取请求,但问题是第一个响应中的数据是在第二个获取请求之后输出的。此外,state: data 设置在 state: recipe 之前,组件使用来自 state: data 的数据进行渲染。

render(){
      return(
        <div className="my-container">
        <EnterCalorie getData={this.getData}/>
        <MealData data={this.state.data} recipe={this.state.recipe}/>
        </div>
      )
    }

如何确保两者同时传下来?

【问题讨论】:

  • 兑现承诺并再次致电

标签: javascript html reactjs fetch-api


【解决方案1】:
fetch(req) // req no1
    .then((response)=>(
        response.json()
    )).then((json)=>{
        console.log(json)
        json.meals.map((obj)=>{
            let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
            let req = new Request(url,{
            method: 'GET',
            headers: header
        })
        fetch(req) // req no 1 called again
        .then((response)=>(
        response.json()
        )).then((json1)=>{
            console.log(json1);
            this.setState((prevState)=>{
                recipe: prevState.recipe.push(json1)
            })
            this.setState(()=>{
                return{
                    data: json
            })
        })
        })
        })

    })

我认为您在第二次 fetch 调用中再次调用具有相同 req 参数的 api

【讨论】:

  • 我正在为两个调用取回我的数据,但state: data 被传递并被渲染出来,然后state: recipe 被获取。
  • 是的,那是因为您在第一次调用本身就完成了 setstate,并且本质上是不同步的,因此您的数据首先更新
【解决方案2】:

在第 3 行返回 return response.json() 而不是什么都没有 (undefined)。

更新:

const toJson = response => response.json()

fetch(req)
    .then(toJson)
    .then(json => {
        this.setState(() => {
            return {
                data: json
            }
        })

        return json
    })
    .then((json) => {
        console.log(json)
        const promises = json.meals.map((obj) => {
            let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
            let req = new Request(url, {
                method: 'GET',
                headers: header
            })
            return fetch(req)
                .then(toJson)
                .then((json) => {
                    console.log(json);
                    this.setState((prevState) => ({
                        recipe: prevState.recipe.push(json)
                    }))
                })
        })

        return Promise.all(promises)
    })
    .then(() => {
        console.log('job done')
    })

你需要将你的数组映射到 Promise 中。然后使用Promise.all 等待他们解决。

括号中缺少:

this.setState((prevState)=>{
    recipe: prevState.recipe.push(json)
})

旁注,这整个东西都应该重构。这种代码风格/代码复杂度你不会走得太远。

【讨论】:

  • 只有一个语句时返回的语法
  • 我收到这个错误:prevState.recipe.push is not a function 和这个Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
  • 这意味着你从错误的地方调用 fetch。从componentDidMount 钩子调用它。
  • *很有可能
  • 我做了一个父组件来解决这个问题。代码绝对是复杂的,我自己也很困惑。感谢您的帮助!
【解决方案3】:

这是一个回调地狱,请寻找Promise races,并检查all() promise 方法。

【讨论】:

    猜你喜欢
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 2016-06-08
    • 2018-12-17
    • 2021-11-09
    相关资源
    最近更新 更多