简体   繁体   English

映射由 React.js 中的组件获取的数组的问题

[英]Problem with mapping an array obtained by a component in React.js

I'm a newbie with React, and I'm trying to understand some basic concepts.我是 React 的新手,我正在尝试理解一些基本概念。 Here's my problem:这是我的问题:

import React from 'react'
import { render } from 'react-dom'

const appkey = 'xxxxxx';

class Message extends React.Component {

    state = { 
        data: []
    }

    componentDidMount() {
        fetch(`https://api.openweathermap.org/data/2.5/weather?q=Toronto,CA&appid=${appkey}`)
        .then(data => data.json())
        // .then((data) => {
        //  console.log(data);
        // })
        .then(data => this.setState({data}))

    }

    componentDidUpdate() {
        console.log("The component just updated")
    }

    render() {
        console.log(this.state.data);
        return (

            <div>
            {this.state.data.map(weather => {
                return (
                    <div key={weather.id}>
                    <h3>Library Product of the Week!</h3>
                    <h4>{weather.name}</h4>
                    <h4>{weather.main.temp}</h4>
                    <h4>{weather.main.feels_like}</h4>
                    <h4>{weather.main.temp_min}</h4>
                    <h4>{weather.main.temp_max}</h4>
                    <h4>{weather.main.pressure}</h4>
                    <h4>{weather.main.humidity}</h4>
                    </div>
                    )
            })}
            </div>
        )
    }
}

render(
    <Message />, 
    document.getElementById('root')
    )

My favorite way is to show the content first then explain the problem.我最喜欢的方式是先展示内容再解释问题。

Like you can see, I use the Openweathermap api just to create some data to show in a component.如您所见,我使用 Openweathermap api 只是为了创建一些数据以显示在组件中。

It works, I was able to console.log the result then the idea is to map the result to show in an html markup.它有效,我能够 console.log 结果然后想法是映射结果以显示在 html 标记中。 The problem is that I'm receiving an error which was this.state.data.map is not a function.问题是我收到一个错误,即 this.state.data.map 不是函数。 I'm not 100% sure on why it is not working because it supposes to be an array, any idea?我不是 100% 确定为什么它不起作用,因为它应该是一个数组,知道吗?

Plus, for some reason the console.log(this.state.data) will produce the same result three times, the first time the data array will be empty, the second and the third the data is like it is supposed to be.另外,由于某种原因,console.log(this.state.data) 将产生相同的结果三次,第一次数据数组为空,第二次和第三次数据就像它应该的那样。

According to the demo in their documentation https://samples.openweathermap.org/data/2.5/weather returns JSON of the form:根据他们文档中的演示https://samples.openweathermap.org/data/2.5/weather返回以下形式的 JSON:

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}

So yes, absolutely not an array.所以是的,绝对不是数组。 So you can actually simplify your code:所以你实际上可以简化你的代码:

render() {
  console.log(this.state.data);
  const weather = this.state.data;
  if (weather && weather.main) {
    return (  
      <div>
        <div key={weather.id}>
          <h3>Library Product of the Week!</h3>
          <h4>{weather.name}</h4>
          <h4>{weather.main.temp}</h4>
          <h4>{weather.main.feels_like}</h4>
          <h4>{weather.main.temp_min}</h4>
          <h4>{weather.main.temp_max}</h4>
          <h4>{weather.main.pressure}</h4>
          <h4>{weather.main.humidity}</h4>
        </div>
      </div>
    )
  } else {
    return (<div>loading..</div>);
  }
}

The response you are getting is an object and map does not work on objects.您得到的响应是一个对象,而map对对象不起作用。 You would need to convert that to array to maps it.您需要将其转换为数组以映射它。 You can use concat function.您可以使用concat函数。

[].concat(this.state.data).map should work. [].concat(this.state.data).map应该可以工作。

Try Bellow试试下面

{[].concat(this.state.data).map(weather => {
            return (
                <div key={weather.id}>
                <h3>Library Product of the Week!</h3>
                <h4>{weather.name}</h4>
                <h4>{weather.main.temp}</h4>
                <h4>{weather.main.feels_like}</h4>
                <h4>{weather.main.temp_min}</h4>
                <h4>{weather.main.temp_max}</h4>
                <h4>{weather.main.pressure}</h4>
                <h4>{weather.main.humidity}</h4>
                </div>
                )
        })}
        </div>

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM