1

这是一个基本的天气应用程序,我正在做它来学习 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 }
  };
}

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

非常感谢您的任何想法!

4

1 回答 1

2

Since WeatherReducer returns an object with data and meta properties, you must declare it as an object in initialState. Your reducer must look like

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

The error might come because initially an empty array is returned as the reducer value before fetchWeather action is triggered and thus this.props.weather.data would be undefined. Another thing to follow in such cases is to conditionally use all of such values which can be undefined at certain point of time

于 2017-12-31T17:05:42.113 回答