简体   繁体   English

如何在redux动作中从axios调用获取数据? React JS搜索项目

[英]How to get data from axios call in redux action? React JS search project

I have a search of weather for some cities. 我正在搜索一些城市的天气。 I would like to create info modal when a user tries to find a city that is not in the base. 当用户尝试查找不在基地中的城市时,我想创建信息模式。 In this case I receive 404 error from my API. 在这种情况下,我从API收到404错误。

I fetch the data every time when user click on search button. 每当用户单击搜索按钮时,我都会获取数据。 I use axios to do it and whole project is based on React and Redux. 我使用axios来做,整个项目都基于React和Redux。 Everything is clear for me but I have a problem with pass valid response to payload . 一切对我来说都是清楚的,但是我对有效payload传递有效响应存在问题。 How should I do it? 我该怎么办? In an another file and use react component lifecycle? 在另一个文件中使用React组件的生命周期?

action.js action.js

export function fetchWeather(city) {
    const url = `${ROOT_URL}&q=${city}`;

    axios.get(url)
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) { 
      console.log(error);
    });

    return {
        type: FETCH_WEATHER,
        payload: request
    };
}

In your example the return will be called before Axios completes it's API call, because it's asynchronous. 在您的示例中,由于Axios是异步的,因此将在Axios完成其API调用之前调用该返回。 One solution to this is to put the return inside the .then like this: 一种解决方案是将返回值放在.then.then如下所示:

export function fetchWeather(city) {
    const url = `${ROOT_URL}&q=${city}`;

    axios.get(url)
    .then(function (response) {
      // won't get called until the API call completes
      console.log(response);
      return {
        type: FETCH_WEATHER,
        payload: response.data
      };
    })
    .catch(function (error) { 
      // won't get called until the API call fails
      console.log(error);
      return {
        type: FETCH_WEATHER_ERROR,
        payload: error
      };
    });
}

You should also return an error in the catch if the API call is unsuccessful. 如果API调用失败,则还应该在catch中返回错误。

In your snippet, request will always be undefined because axios.get is an async operation and return happens before axios.get finishes execution. 在您的代码段中, request将始终是undefined因为axios.get是异步操作,并且returnaxios.get完成执行之前发生。 You do something like this: 您可以执行以下操作:

export async function fetchWeather(city) {

  try {
    const request = await axios.get(`${ROOT_URL}&q=${city}`);
    // server returned a 2XX response (success)
    return {
      type: FETCH_WEATHER,
      payload: request
    };
  } catch(error) {
    // Network failure or 4XX or 5XX response.
    return {
      type: FETCH_WEATHER_FAIL
      payload: error
    }
  }
}

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

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