Javascript 如何在redux操作中从axios调用获取数据?React JS搜索项目
我搜索了一些城市的天气。我想创建一个信息模式,当用户试图找到一个城市,不在基地。在这种情况下,我从API接收到Javascript 如何在redux操作中从axios调用获取数据?React JS搜索项目,javascript,reactjs,redux,axios,Javascript,Reactjs,Redux,Axios,我搜索了一些城市的天气。我想创建一个信息模式,当用户试图找到一个城市,不在基地。在这种情况下,我从API接收到404错误 每次用户单击搜索按钮时,我都会获取数据。我使用axios来完成它,整个项目都基于React和Redux。对我来说一切都很清楚,但是我对有效负载的pass-valid响应有问题。 我该怎么做?在另一个文件中并使用react组件生命周期 action.js export function fetchWeather(city) { const url = `${ROOT_U
404
错误
每次用户单击搜索按钮时,我都会获取数据。我使用axios
来完成它,整个项目都基于React和Redux。对我来说一切都很清楚,但是我对有效负载的pass-valid响应有问题。
我该怎么做?在另一个文件中并使用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
};
}
在您的示例中,将在Axios完成其API调用之前调用该返回,因为它是异步的。一种解决方法是将返回值放入中。然后像这样:
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
};
});
}
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
}
}
}
如果API调用不成功,您还应该在catch中返回一个错误。在您的代码段中,请求
将始终是未定义的
,因为axios.get
是一个异步操作,返回
发生在axios.get
完成执行之前。你可以这样做:
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
};
});
}
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
}
}
}
你不能改用fetch吗?谢谢你的修复@trixn