根据第一个 api React js 的响应从第二个 api 获取数据

Fetching the data from second api based on the response from the first api React js

我打算在我的 React 项目中使用来自第一个 api 的数据调用第二个 api 我尝试使用单个 useState 并使用 axios 链接承诺,但它似乎不是正在工作,因为我想基本上根据第一个 api id 值

从第二个 api 中过滤掉数据

Api 1

[{
    id: 01,
    title: Post title One,
    external_id: 101
},
{
    id: 02,
    title: Post title Two,
    external_id: 102
},
{
    id: 03,
    title: Post title Three,
    external_id: 103
}]

Api 2

[{
    id: 101,
    image: Image Url,
},
{
    id: 102,
    image: Image Url,
},
{
    id: 103,
    image: Image Url,
}]

我希望它们并排工作,然后将它们作为 props 传递,以根据来自两个 API 的数据呈现项目。这是我尝试过的,我知道这段代码不正确,但我被困在这里了。这是我的 React 代码

const App = () => {

    const [posts, setPosts] = useState([]);
    const [postsExternal, setPostsExternal] = useState([]);


    useEffect(() => axios.get(`http://localhost:2000/posts`)
    .then(response => {
        setPosts(response.data);
        return response.data.external_id;
    })
    .then(getExternalId => axios.get(`http://localhost:2000/posts/${getExternalId}`))
    .then(response => {
        setPostsExternal(response.data);
    }), []);


    return (
        <div>
            <Posts posts={posts} postsExternal={postsExternal}/>
        </div>
    )
}

export default App

您得到的是一个数组,而不是单个对象。修改 useEffect 以使用 Promise.all() 调用 API:

useEffect(() => {
    axios.get(`http://localhost:2000/posts`)
    .then(response => {
        setPosts(response.data);
        return response.data.map(({external_id}) => external_id);
    })
    .then(externalIds => {
     return Promise.all(externalIds
                   .map(externalId => axios.get(`http://localhost:2000/posts/${externalId}`)))
    })
    .then(response => {
        setPostsExternal(response.data);
    }), 
}, []);

我已经阅读了您的代码,问题是您的代码排列有点错位。还因为您正在获取一组数据,并且需要使用 external_id 对该数组中的每个数据进行调用

我建议您尝试不同的方法。试试下面的代码片段(包含注释以便更好地理解):

谢谢。

import React, { useState, useEffect } from "react";
import axios from "axios";



const YourApp = () => {
  const [posts, setPosts] = useState([]);
  const [postsExternal, setPostsExternal] = useState([]);

 
  useEffect(() => {
    // not adding .catch() here for simplicity 

    axios.get(`http://localhost:2000/posts`).then(({ data }) => {
      // we're putting this here because we only want to set state once (we don't wanna have to rerender 30times in data.map())
      let externalPosts = [];
      // destructed out the {data}, same as response.data, so no worries 
      setPosts(data);
      console.log(data);
      // this is where you'll make your second API calls using the external_id from first call
      data.map(({ external_id }) => {
        // {external_id} same as your-param-name.external_id
        axios
          .get(`http://localhost:2000/posts/${external_id}`)
          .then(({ data }) => {
            // we push the data into the array 
            console.log(data);
            externalPosts.push(data);
          });

        // then finally set the external post states once to prevent multiple rerendring in .map() 
        setPostsExternal(externalPosts);
        // that's it 
      });
    });

    // tho, i'd recommend you create a seperate function for the above 
  }, []);

  return (
    <div>
      <Posts posts={posts} postsExternal={postsExternal} />
    </div>
  );
};

export default YourApp;