正在获取未定义的JSON路径,但数据在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]...。如果映射操作中的weather实际上是一个对象而不是数组,那么这将不起作用。我想你想要的是下面这样的东西。注意,为了清楚起见,我已将内部变量的名称更改为weatherItem

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

最新更新