Почему mapStateToProps не выводит значение из массива?



@AxelKroos

Добрый день 🙂
Столкнулся вот с такой проблемой:

Есть компонент Weather

import React from 'react'
import classes from './weather.module.css'
import {connect} from "react-redux";

class Weather extends React.Component {
    render() {
        return (
            <div className={classes.weather}>
                {this.props.other.city}
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    debugger
    return {
        other: state.currentWeather.other
    }
}

function mapDispatchToProps(dispatch) {
    return null
}

export default connect(mapStateToProps, mapDispatchToProps)(Weather);

И сам редюсер

import {CURRENT_CITY, ADD_CITY} from "./actions/actionTypes";
const initialState = {
    currentValue: '777',
    other: [{
        city: 'Gotham'
    }],
}

export default function currentWeather(state = initialState, action) {

    switch (action.type) {
        case CURRENT_CITY:
            return {
                currentValue: action.payload
            }
        case ADD_CITY:
            const addWeather = async () => {
                const api_key = '0a18303f01a73e215e930966eb1a77bc'
                const city = state.currentValue
                const api_url = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api_key}&units=metric`)
                const data = await api_url.json()
                if (data.cod == '400' || data.cod == '404') {
                    return null
                }
                initialState.other.push({
                    city: data.name,
                    country: data.sys.country,
                    temp: data.main.temp,
                    humidity: data.main.humidity,
                    wind: data.wind.speed,
                    feelsLike: data.main.feels_like
                })
            }
            addWeather()
            return {
                currentValue: ''
            }
        default:
            return state
    }
}

Вопрос: почему в компоненте Weather {this.props.other.city} является undefined?


Решения вопроса 1



@profesor08

Потому что this.props.other является массивом, а у массива нет такого свойства как city. Оно есть у элементов этого массива.

P.S. Используй TypeScript, с ним подобные недопонимания отпадут.



1

комментарий


Ответы на вопрос 0

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *