获取未定义的 JSON 路径,但数据在 console.log 中可用

Getting undefined JSON path, but data is available in console.log

我是第一次使用 Redux Toolkit。数据在控制台中成功可用,但是当我尝试在 UI 中呈现数据时,我得到未定义的 JSON 路径 {${weather[0].description} ${weather[0].main}} 也许我需要用 if( ) 声明,但我不知道如何以及在哪里。我自己的 if() 解决方案在 App.js

中没有成功

JSON数据

description: "broken clouds"
icon: "04n"
id: 803
main: "Clouds"
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)

App.js边

import { useDispatch, useSelector } from 'react-redux';
import { fetchWeatherAction } from './redux/slices/weatherSlices';


function App() {
  const dispatch = useDispatch();
  
  useEffect(() => {
    dispatch(fetchWeatherAction('Seoul'));
  }, []);
  
  const state = useSelector(state => state.weather);
  const { loading, weather, error } = state || {};

  if(!weather){
    return null
  }

  console.log(weather);

  return (
    <div className="App">
      <header className="App-header">
      {weather.map((weather, index) => (
        <div key={index}>
          <div>{`${weather[0].description} ${weather[0].main}`}</div>
        </div>
      ))}
      </header>
    </div>
  );
}

export default App;```


Redux Toolkit side

``` import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
 import axios from 'axios';

 export const fetchWeatherAction = createAsyncThunk(
        'weather/fetch',
        async (payload, {rejectWithValue, getState, dispatch})=>{
            try{
                const {data} = await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=${payload}&appid=7469e38d322111e34a7027db2eee39c3`);
                return data;
            }catch(error){
                if(!error?.response){
                    throw error
                }
                return rejectWithValue(error?.response?.data);
            }
        }
 );

    const weatherSlice = createSlice({
        name: 'weather',
        initialState: {},
        extraReducers: builder => {
            builder.addCase(fetchWeatherAction.pending, (state, action) => {
                state.loading = true;
            });
            builder.addCase(fetchWeatherAction.fulfilled, (state, action) => {
                state.weather = action?.payload;
                state.loading = false;
                state.error = undefined;
            });
            builder.addCase(fetchWeatherAction.rejected, (state, action) => {
                state.loading = false;
                state.weather = undefined;
                state.error = action?.payload;
            })
        },
    });

    export default weatherSlice.reducer;```

您似乎正在映射 weather,它看起来像一个对象数组,然后试图索引到该对象,例如weather[0]...。如果 map 操作中的 weather 实际上是一个对象而不是数组,这将不起作用。我认为您想要的是以下内容。请注意,为了清楚起见,我已将内部变量的名称更改为 weatherItem

{weather.map((weatherItem, index) => (
  <div key={index}>
    <div>{`${weatherItem.description} ${weatherItem.main}`}</div>
  </div>
))}