【问题标题】:How do i set the state from one API call and use the data for URL in next API call?如何从一个 API 调用设置状态并在下一个 API 调用中使用 URL 数据?
【发布时间】:2019-05-31 04:56:00
【问题描述】:

我需要来自 API 调用 1 的数据添加到 API 调用 2 的 URL。来自 API 2 的数据将进入 API 3 的 URL。我正在设置每个 Axios 请求的状态,但它不起作用。返回未定义

componentDidMount() {
  // Get the IP adress of user
  axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
      this.setState({
        ip: res.data.ip
      });
      console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));

  // GET the coordinates of a location based on IP adress
  axios
    .get(
      'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
    )
    .then(res => {
      this.setState({
        latitude: res.data.location.lat,
        longitude: res.data.location.lng
      });
      console.log(
        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
      );
    })
    .catch(err => console.log(err));

  // Make the API call on page load
  axios({
      method: 'get',
      url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Accept: 'application/json',
        'user-key': 'USER_KEY'
      }
    })
    .then(res => {
      const restaurantsNearMe = res.data.nearby_restaurants;

      this.setState({
        restaurants: restaurantsNearMe
      });

      // Pick out a random retaurant from what the API returns
      var randomRestaurant =
        restaurantsNearMe[
          Math.floor(Math.random() * restaurantsNearMe.length)
        ];

      // Select only the data that you want
      var finalResult = {
        name: randomRestaurant.restaurant.name,
        id: randomRestaurant.restaurant.id,
        rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
        ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
        address: randomRestaurant.restaurant.location.address,
        delivery: randomRestaurant.restaurant.is_delivering_now,
        typeOfFood: randomRestaurant.restaurant.cuisines
      };

      this.setState({
        restaurant: finalResult
      });
      console.log(this.state.restaurant);
    })
    .catch(err => console.log(err));
}

【问题讨论】:

标签: reactjs async-await axios


【解决方案1】:

您需要在setState 中添加一个callback,在该callback 中您需要调用您的第二个API,依此类推。检查this

这就是你想要的,

axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
        this.setState({
            ip: res.data.ip
        }, () => {
            // GET the coordinates of a location based on IP adress
            axios
                .get(
                    'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
                )
                .then(res => {
                    this.setState({
                        latitude: res.data.location.lat,
                        longitude: res.data.location.lng
                    }, () => {
                        // Make the API call on page load
                        axios({
                                method: 'get',
                                url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                    Accept: 'application/json',
                                    'user-key': 'USER_KEY'
                                }
                            })
                            .then(res => {
                                const restaurantsNearMe = res.data.nearby_restaurants;

                                this.setState({
                                    restaurants: restaurantsNearMe
                                });

                                // Pick out a random retaurant from what the API returns
                                var randomRestaurant =
                                    restaurantsNearMe[
                                        Math.floor(Math.random() * restaurantsNearMe.length)
                                    ];

                                // Select only the data that you want
                                var finalResult = {
                                    name: randomRestaurant.restaurant.name,
                                    id: randomRestaurant.restaurant.id,
                                    rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
                                    ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
                                    address: randomRestaurant.restaurant.location.address,
                                    delivery: randomRestaurant.restaurant.is_delivering_now,
                                    typeOfFood: randomRestaurant.restaurant.cuisines
                                };

                                this.setState({
                                    restaurant: finalResult
                                });
                                console.log(this.state.restaurant);
                            })
                            .catch(err => console.log(err));
                    });
                    console.log(
                        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
                    );
                })
                .catch(err => console.log(err));

        });
        console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));

【讨论】:

    【解决方案2】:

    要记住一件事,this.setState 不是同步的。 React 批处理多个设置状态调用以提高渲染性能。这就是为什么您可能会在 console.log 中看到未定义的原因。 setState 方法将回调作为第二个参数。

    this.setState(newState, callbalck)

    所以尝试控制台登录回调并试一试。

    【讨论】:

      【解决方案3】:

      我不知道你是如何调用 API 的,但是,试试这样的:

      componentDidMount 你可以这样做:

      async componentDidMount(){
        const resApiOne = await callFirstApi();
        this.setState({resApiOne});
        const resApiTwo = await callSecondApi(resApiOne);
        this.setState({resApiTwo});
      }
      

      【讨论】:

        猜你喜欢
        • 2022-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-06
        • 2021-02-02
        • 1970-01-01
        • 2020-09-14
        • 2020-12-08
        相关资源
        最近更新 更多