我正在构建一个返回特定城市天气详情的天气应用程序。输入有效位置时一切正常。当我在搜索字段中输入垃圾字符串(例如'afasdfldsakfh')并按回车键时,会出现问题。这是有道理的,因为api调用不应该找到位置。
我在控制台中收到以下错误:
Uncaught TypeError: Cannot read property 'observation_location' of undefined
这来自RECEIVE_WEATHER案例下的reducer。当有效负载无效并且缺少为我的状态设置道具时需要的信息时,我不确定我需要做什么。非常感谢任何帮助,谢谢!
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
};
};
答案 0 :(得分:1)
在你的提取调用中使用附加错误处理程序,如下所示:
return fetch(weatherUrl + location + '.json', init)
.then(response => response.json())
.then(json => dispatch(receiveWeather(json)))
.catch(err => handleError(err))
我不知道你正在使用fetch
的实现方式,但api上通常有catch
或error
方法。
您还可以添加处理错误的案例:
case RECEIVE_WEATHER_ERROR:
return ...
在这种情况下,你也可以在错误处理程序
中调度错误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
...