ReduxToolkit 中的错误无法处理 API 错误

Error in ReduxToolkit can't handle API error

我有一个 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.

您可以查看 here

中的所有代码

额外的减速器

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
        },

redux 调用

const [country, setCountry] = useState(undefined)
const {getData: APIData ,isLoading} = useSelector(state => state.getDataSlice)
    useEffect(() => {
        dispatch(getDataReducer({country}))
    },[dispatch, country])

任何帮助,请

由于请求未定义而发生此错误

<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}
        />

这就是我更改代码的方式,但您可以将其重新发布为更清晰的代码。

我也在 codesandbox 中进行了更改。

https://codesandbox.io/embed/quiet-browser-qiqtm7?fontsize=14&hidenavigation=1&theme=dark

最佳。