Estoy usando Redux Toolkit por primera vez. Los datos están disponibles correctamente en la consola, pero cuando trato de representar datos en la interfaz de usuario, obtengo una ruta JSON indefinida { ${weather[0].description} ${weather[0].main} } verifique algo con la declaración if() pero no sé cómo y dónde. Mi propia solución if() no funcionó en App.js
datos JSON
description: "broken clouds" icon: "04n" id: 803 main: "Clouds" [[Prototype]]: Object length: 1 [[Prototype]]: Array(0)Lado de 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;```Parece que está mapeando weather , que parece una matriz de objetos, y luego intenta indexar ese objeto como, por ejemplo, weather[0]... . Si el weather dentro de la operación del mapa es de hecho un objeto y no una matriz, esto no funcionará. Creo que lo que quieres es algo como lo siguiente. Tenga en cuenta que he cambiado el nombre de la variable interior a weatherItem para mayor claridad:
{weather.map((weatherItem, index) => ( <div key={index}> <div>{`${weatherItem.description} ${weatherItem.main}`}</div> </div> ))}