如何通过映射反应API的值?

时间:2017-01-22 15:46:03

标签: api reactjs superagent

我想从天气API中渲染多个对象(天)

const  myApi = 'http://api.openweathermap.org/data/2.5/forecast?q=London,gb&APPID=MY_UNIQUE_ID&cnt=5'

我在APP类中设置这些值的原始状态:

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      locationName: 'your local area',
      displayUnits: 'F',
      locTemp: '',
      humidity: '',
      weatherSummary: '',
      weatherSummaryDescription: '',
      dayID: '',
      dateFor: '',
      everyDay: []
    };
  }

然后我使用新的状态设置这些值,其中大多数是从API中获取的:

componentWillMount() {
      superagent.get(myApi).then((response) => {
          console.log('CITY NAME IS' + response.body.city.name)
          console.log('RESPONSE BODY IS' + response.body)
        this.setState({
          locationName: response.body.city.name,
          locTemp: response.body.list[0].main.temp,
          humidity: response.body.list[0].main.humidity,
          weatherSummary: response.body.list[0].weather[0].main,
          weatherSummaryDescription: response.body.list[0].weather[0].description,
          dayID: response.body.list[0].dt,
          dateFor: response.body.list[0].dt_txt,
          everyDay: response.body

        })


      });

  }

我为渲染功能

创建了一个函数输出
export default class MyForecast extends React.Component {

  constructor(props) {
   super(props);
   this.state = {
     displayUnits: props.displayUnits
  };
}



  render() {

    return (
      <div>
        <h1>Weather for&nbsp;{this.props.locationName}</h1>
        <h3> on {this.props.dateFor}</h3>
        <h2>
            {this.props.weatherSummaryDescription} &nbsp;
            <Temp temp={this.props.locTemp} displayUnits={this.props.displayUnits} clickHandler={this.toggleDisplayUnits.bind(this)}/>
        </h2>
        <WeatherIcon weather={this.props.weatherSummary} />
        <p>The ID for this day is <strong>{this.props.dayID}</strong></p>
      </div>);
  }


  toggleDisplayUnits() {
    this.state.displayUnits === 'F' ? this.setState({
      displayUnits: 'C'
    }) : this.setState({
      displayUnits: 'F'
    });
  }

}

然后在APP中我钻取everyDay对象,以便生成5个具有5个不同对象的MyForecast实例

render() {

     return (
       <div>
         {this.state.everyDay.map((data, i) =>
           <MyForecast
             key={i}
             locationName={data.locationName}
             dateFor={data.dateFor}
             weatherSummaryDescription={data.weatherSummaryDescription}
             weatherSummary={data.weatherSummary}
             locTemp={data.locTemp}
             dayID={this.state.dayID}/>
         )}
       </div>
     );
  }

这导致2个错误:

Uncaught TypeError: this.state.everyDay.map is not a function

并且

Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null

因为它没有everyDay(body.response)的值,因为它是错误的格式(不是数组)

有关如何以正确方式执行此操作的任何想法?

JSON格式:

"city": {
    "id": 2643743,
    "name": "London",
    "coord": {
      "lon": -0.12574,
      "lat": 51.50853
    },
    "country": "GB",
    "population": 0,
    "sys": {
      "population": 0
    }
  },
  "cod": "200",
  "message": 0.1174,
  "cnt": 5,
  "list": [
    {
      "dt": 1485097200,
      "main": {
        "temp": 279.16,
        "temp_min": 278.192,
        "temp_max": 279.16,
        "pressure": 1033.03,
        "sea_level": 1040.8,
        "grnd_level": 1033.03,
        "humidity": 75,
        "temp_kf": 0.97
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01d"
        }
...

1 个答案:

答案 0 :(得分:0)

这会有效吗?

componentWillMount() {
  superagent.get(myApi).then((response) => {
    this.everyDAY = response.body;
  }
}

然后在渲染中:

 return (
   <div>
     {this.everyDay.list.map((data, i) =>
       <MyForecast
         key={i}
         locationName={this.everyDay.city.name}
         dateFor={data.dt_txt}
         weatherSummaryDescription={data.weather[0].description}
         weatherSummary={data.weather[0].main}
         locTemp={data.main.temp}
         dayID={data.dayID}/>
     )}
   </div>
 );