访问作为对象的 reducer 有效负载的元素

Accessing elements of reducer payload that is an object

这是我为学习 Redux 而做的一个基本的天气应用程序。 API 没有提供搜索的城市名称,所以我必须通过 Redux 传递它。

我有以下容器:

import React, { Component } from "react";
import { connect } from "react-redux";

class WeatherList extends Component {
  renderWeather = cityData => {
    const conditions =
      cityData.forecast.simpleforecast.forecastday[0].conditions;
    const fHigh =
      cityData.forecast.simpleforecast.forecastday[0].high.fahrenheit;
    return (
      <tr>
        {/* <td>{cityData.city}</td> */}
        <td>{cityData.meta.city}</td>
        <td>{conditions}</td>
        <td>{fHigh}</td>
      </tr>
    );
  };
  render() {
    return (
      <table className="table table-hover">
        <thead>
          <tr>
            <th>City</th>
            <th>Conditions</th>
            <th>High (F)</th>
            <th>Humidity</th>
          </tr>
        </thead>
        {/* <tbody>{this.props.weather.map(this.renderWeather)}</tbody> */}
        <tbody>{this.props.weather.data.map(this.renderWeather)}</tbody>
      </table>
    );
  }
}

const mapStateToProps = ({ weather }) => ({
  weather
});

export default connect(mapStateToProps)(WeatherList);

this.props.weather.data.map 抛出 "cannot read property map of undefined" 错误。

提供 "weather" 状态的减速器是:

import { FETCH_WEATHER } from "../actions/index";

export function WeatherReducer(state = [], action) {
  switch (action.type) {
    case FETCH_WEATHER:
      console.log(action.payload.data);
      console.log(action.meta.city);
      return { data: [action.payload.data, ...state], meta: action.meta.city };
    // return [action.payload.data, ...state];
  }
  return state;
}

最后是相关的动作创建者:

import axios from "axios";

const API_KEY = "e95fb12f6c69ae61";
const ROOT_URL = `http://api.wunderground.com/api/${API_KEY}/forecast/q/`;

export const FETCH_WEATHER = "FETCH_WEATHER";

export function fetchWeather(searchData) {
  const url = `${ROOT_URL}${searchData.stateName}/${searchData.city}.json`;
  const request = axios.get(url);

  return {
    type: FETCH_WEATHER,
    payload: request,
    meta: { city: searchData.city }
  };
}

您可以从注释掉的代码中看出,如果我只传递一个数组进行迭代,我就可以让它工作。但我需要传递更多信息才能获得一个人搜索的城市名称。我该怎么做才能读取状态对象的第一个元素数组,并消除未定义的错误?

非常感谢任何想法!

由于 WeatherReducer returns 是一个具有数据和元属性的对象,您必须在 initialState 中将其声明为一个对象。您的减速器必须看起来像

const initialState = {
    data: [],
    meta: ''
}
export function WeatherReducer(state = initialState, action) {
  switch (action.type) {
    case FETCH_WEATHER:
      console.log(action.payload.data);
      console.log(action.meta.city);
      return { data: [action.payload.data, ...state.data], meta: action.meta.city };
  }
  return state;
}

可能会出现错误,因为在触发 fetchWeather 操作之前,最初返回一个空数组作为 reducer 值,因此 this.props.weather.data 将是 undefined。在这种情况下要遵循的另一件事是有条件地使用所有这些在特定时间点可能未定义的值