如何从redux中调用axios调用数据? React JS搜索项目

时间:2018-04-23 14:04:34

标签: javascript reactjs redux axios

我搜索了一些城市的天气。当用户试图找到不在基地的城市时,我想创建信息模态。在这种情况下,我的API会收到404错误。

每次用户点击搜索按钮时,我都会获取数据。我使用axios来完成它,整个项目基于React和Redux。对我来说一切都很清楚,但我对payload的有效回复有问题。 我该怎么办?在另一个文件中并使用react组件生命周期?

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
    };
}

2 个答案:

答案 0 :(得分:2)

在您的示例中,将在Axios完成其API调用之前调用返回,因为它是异步的。对此的一个解决方案是将回报放在.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
      };
    });
}

如果API调用不成功,您还应该在catch中返回错误。

答案 1 :(得分:1)

在您的代码段中,public class SeedData { public SeedData() { } public static async Task Seeding(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager, ApplicationDbContext context) { if (!context.Roles.Any()) { context.Roles.AddRange( new ApplicationRole { Id = "b562e963-6e7e-4f41-8229-4390b1257hg6", Description = "This Is AdminUser", Name = "Admin", NormalizedName = "ADMIN" }); context.SaveChanges(); } if (!context.Users.Any()) { ApplicationUser user = new ApplicationUser { FirstName = "MyFirstName", LastName = "MyLastName", PhoneNumber = "9998885554", UserName = "saedbfd", NormalizedUserName = "SAEDBFD", Email = "MyEmail@Email.com", NormalizedEmail="MYEMAIL@EMAIL.COM", gender = 1, PasswordHash = "AQAAAAEAACcQAAAAEH9MTIiZG90QJrMLt62Zd4Z8O5o5MaeQYYc/53e2GbawhGcx2JNUSmF0pCz9H1AnoA==", LockoutEnabled = true, SecurityStamp = "aea97aa5-8fb4-40f2-ba33-1cb3fcd54720" }; context.Users.Add(user); context.SaveChanges(); IdentityUserRole<string> ur = new IdentityUserRole<string>(); ur.RoleId = "b562e963-6e7e-4f41-8229-4390b1257hg6"; ur.UserId = user.Id; context.UserRoles.Add(ur); context.SaveChanges(); } } 始终为request,因为undefined是异步操作,axios.getreturn完成执行之前发生。你做这样的事情:

axios.get