私は特定の都市の天気詳細を返す天気アプリを構築しています。有効な場所が入力されると、すべて正常に動作します。私の問題は、検索フィールドに迷惑ストリング(例: 'afasdfldsakfh')を入力してEnterキーを押すと発生します。これはapi呼び出しが場所を見つけてはならないので理にかなっています。fetchを呼び出すときにエラーを処理する
私は、コンソールで次のエラーを取得する:
Uncaught TypeError: Cannot read property 'observation_location' of undefined
これはRECEIVE_WEATHERケースの下に減速から来ています。私はペイロードが有効ではなく、私の状態のための小道具を設定する必要がある情報が欠落しているときに何をする必要があるかわからない。どんな助けも大変ありがとうございます。
return fetch(weatherUrl + location + '.json', init)
.then(response => response.json())
.then(json => dispatch(receiveWeather(json)))
.catch(err => handleError(err))
私はあなたが使用しているfetch
のものを実装知らないが、catch
またはerror
方法は、APIで、一般的にあります:あなたの呼び出しフェッチの使用において
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
};
};
感謝を。 package.jsonファイルにフェッチの実装が表示されません。しかし、私は 'whatwg-fetch'がnode_modulesフォルダにあります。私はこの反応骨格を使用しています:https://github.com/joellongie/dustDevil。私は '.catch(err ...')行を追加した後にhandleError関数を呼び出せないようです。戻りの前にconsole.log( 'hello')を試してみましたが、何もありません。 – Banner
@Banner Try '。 .catchの代わりにerror(err => dispatch(handleError(err)) 'の代わりに.catch – JoshSGman
これをコンソールで取得する:Uncaught TypeError:fetch(...)、then(...)。関数ではない – Banner