gpt4 book ai didi

javascript - 在 redux 中进行 fetch 调用时处理错误

转载 作者:行者123 更新时间:2023-12-03 06:07:00 27 4
gpt4 key购买 nike

我正在构建一个天气应用程序,它返回特定城市的天气详细信息。输入有效位置后一切正常。当我在搜索字段中输入垃圾字符串(例如“afasdfldsakfh”)并按 Enter 键时,就会出现问题。这是有道理的,因为 api 调用不应找到该位置。

我在控制台中收到以下错误:

Uncaught TypeError: Cannot read property 'observation_location' of undefined

这来自 RECEIVE_WEATHER 情况下的 reducer 。我不确定当有效负载无效并且缺少为我的状态设置 Prop 所需的信息时我需要做什么。任何帮助将不胜感激,谢谢!

export function receiveWeather(json) {
console.log(json);
return {
type: RECEIVE_WEATHER,
payload: json
};
};

export function fetchingWeather(location) {
const init = {
method: 'GET'
};
return dispatch => {
dispatch(requestWeather())
return fetch(weatherUrl + location + '.json', init)
.then(response => response.json())
.then(json => dispatch(receiveWeather(json)))
};
};

export function weather(state = {
isFetching: false,
city: '',
country: '',
weather_image: '',
weather_description: '',
weather_number: '',
wind_dir: '',
wind_speed: '',
humidity: '',
precipitation: ''
}, action) {
switch (action.type) {
case REQUEST_WEATHER:
return Object.assign({}, state, {
isFetching: true
});
case RECEIVE_WEATHER:
return Object.assign({}, state, {
isFetching: false,
city: (action.payload.current_observation.observation_location.full),
country: (action.payload.current_observation.observation_location.country),
weather_image: (action.payload.current_observation.icon_url),
weather_description: (action.payload.current_observation.weather),
weather_number: (action.payload.current_observation.temp_c),
wind_dir: (action.payload.current_observation.wind_dir),
wind_speed: (action.payload.current_observation.wind_kph),
humidity: (action.payload.current_observation.relative_humidity),
precipitation: (action.payload.current_observation.precip_today_in)
});
default:
return state
};
};

最佳答案

在您的 fetch 调用中使用附加错误处理程序,如下所示:

return fetch(weatherUrl + location + '.json', init)
.then(response => response.json())
.then(json => dispatch(receiveWeather(json)))
.catch(err => handleError(err))

我不知道您使用的 fetch 的实现是什么,但 API 上通常有一个 catcherror 方法。

您还可以添加一个处理错误的案例,如下所示:

case RECEIVE_WEATHER_ERROR: 
return ...

在这种情况下,您也可以在错误处理程序中分派(dispatch)错误

return fetch(weatherUrl + location + '.json', init)
.then(response => response.json())
.then(json => dispatch(receiveWeather(json)))
.catch(err => dispatch(handleError(err)))

handleError 可以像其他函数一样实现:

function handleError(err) {
return {
type: RECEIVE_WEATHER_ERROR,
payload: err
}
}

如果您没有收到错误,而是收到一个空的 json 对象,其中 payload.current_observation 未定义

在您的案例陈述中添加以下内容:

case RECEIVE_WEATHER:
if (!action.payload.current_observation) return state
...

关于javascript - 在 redux 中进行 fetch 调用时处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39498617/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com