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

时间:2017-12-31 16:43:05

标签: javascript reactjs react-redux redux-promise

这是我正在学习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抛出“无法读取未定义属性映射”的错误。

提供“天气”状态的减速器是:

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 }
  };
}

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

非常感谢任何想法!

1 个答案:

答案 0 :(得分:2)

由于WeatherReducer返回具有数据和元属性的对象,因此必须将其声明为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。在这种情况下要遵循的另一件事是有条件地使用所有这些在某个时间点可能未定义的值