如果异步访问API调用中的项目列表

时间:2018-08-11 06:21:48

标签: javascript html reactjs api

我正在使用React和Redux构建天气应用程序。当我想显示给定城市未来5天的天气时,我会进行API调用,该API将获得一个小时序列的几个天气参数的列表。我只能访问list [0]元素中包含的内容,因为尚未创建其他内容。如何访问它们?我考虑过设置间隔功能,但无法设置。有什么建议吗?

天气部分

import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
import GoogleMap from '../components/google_map';

class WeatherList extends Component {
    renderWeather(cityData) {
        const temps = _.map(cityData.list.map(weather => weather.main.temp), (temp) => temp - 273);
        const pressure = cityData.list.map(weather => weather.main.pressure);
        const humidity = cityData.list.map(weather => weather.main.humidity);
        const day1 = cityData.list[0].weather[0].description;
        const day2 = cityData.list[1].weather[2].description;
        const day3 = cityData.list[2].weather[2].description;         
        const lon = cityData.city.coord.lon;
        const lat = cityData.city.coord.lat;

        return (
            <tr key={cityData.city.name}>
                <td><GoogleMap lon={lon} lat={lat}/></td>
                <td>{day1}</td>
                <td>{day2}</td>
                <td>{day3}</td>
                <td><Chart data={temps} color="orange" units="°"/></td>
                <td><Chart data={pressure} color="yellow" units="hPa"/></td>
                <td><Chart data={humidity} color="green" units="%"/></td>

            </tr>
        );
    }

    render() {
        return (
            <table className="table table-hover">
                <thead>
                    <tr>
                        <th>City</th>
                        <th>Overall Weather</th>
                        <th>Pressure (hPa)</th>
                        <th>Humidity (%)</th>
                        <th>Temperature (k)</th>
                    </tr>
                </thead>
                <tbody>
                    {this.props.weather.map(this.renderWeather)}
                </tbody>
            </table>
        )
    }
}

function mapStateToProps(state) {
    return { weather: state.weather };
}

export default connect(mapStateToProps)(WeatherList);

API调用操作创建者

import axios from 'axios';

const API_KEY = 'ce6111c5cb481755173214d6bf62f51a';
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`;

export const FETCH_WEATHER = 'FETCH_WEATHER';

export function fetchWeather(city) {
    const url = `${ROOT_URL}&q=${city},it`;
    const request = axios.get(url);

    return {
        type: 'FETCH_WEATHER',
        payload: request
    };
}

FETCH_WEATHER呼叫的减少器

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

export default function (state= [], action) {
    switch (action.type) {

    case FETCH_WEATHER:
        return state.concat([action.payload.data]);    
    }     
    return state;
}

image of the list

0 个答案:

没有答案