我有一個天氣應用程式的 API 我正在嘗試正確連接它但是我通過在輸入欄位中輸入錯誤的值來測驗它我收到錯誤但在輸入錯誤資料時無法解決此錯誤
像這樣的錯誤:
在Dashboard.js:55
Uncaught TypeError: Cannot read properties of undefined (reading '0')
和
Consider adding an error boundary to your tree to customize error handling behavior.
你可以從這里檢查所有代碼
額外的減速器
export const getDataReducer = createAsyncThunk('weatherData/getData', async (args, thunkAPI) => {
const { rejectWithValue } = thunkAPI;
try {
const data = await axios.get(`https://api.worldweatheronline.com/premium/v1/weather.ashx?key=${api_key}&q=${args.country}&format=json&num_of_days=5`, {
headers: {...}
})
.then(res => res.data)
.catch(e => console.log("fetchError",e))
console.log('new new new',data)
return data
} catch (error) {
return rejectWithValue(error.message)
}
})
片
[getDataReducer.pending]: (state, action) => {
state.isLoading = true
},
[getDataReducer.fulfilled]: (state, action) => {
state.isLoading = false
state.error = false
state.getData = action?.payload?.data
},
[getDataReducer.rejected]: (state, action) => {
state.isLoading = false
state.error = true
state.getData = action?.payload?.data
},
還原呼叫
const [country, setCountry] = useState(undefined)
const {getData: APIData ,isLoading} = useSelector(state => state.getDataSlice)
useEffect(() => {
dispatch(getDataReducer({country}))
},[dispatch, country])
任何幫助,請
uj5u.com熱心網友回復:
由于請求未定義而發生此錯誤
<WeatherInfo
isLoading={isLoading}
city={APIData && APIData.request ? APIData.request[0]?.query?.split(',')[0] : ''}
country={APIData && APIData.request ? APIData.request[0]?.query?.split(',')[1] : ''}
latitude={latitude}
longitude={longitude}
/>
<Temp
isLoading={isLoading}
celsius={APIData && APIData.current_condition ? APIData.current_condition[0]?.temp_C : ''}
fahrenheit={APIData && APIData.current_condition ? APIData.current_condition[0]?.temp_F : ''}
weatherStatus={APIData && APIData.current_condition && APIData.current_condition[0].weatherDesc ? APIData.current_condition[0].weatherDesc?.value : ''}
ForC={ForC}
setForC={setForC}
/>
這就是我更改代碼的方式,但您可以將其重新發布到更清晰的代碼。
我也在代碼沙箱中進行了更改。
https://codesandbox.io/embed/quiet-browser-qiqtm7?fontsize=14&hidenavigation=1&theme=dark
最好的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/483145.html
標籤:javascript 反应 还原 反应还原 redux 工具包
