API请求无限。为什么?

时间:2018-06-24 13:07:55

标签: reactjs api request fetch

我创建天气应用程序并使用API​​ openweathermap。 我从API获取数据,但控制台中的网络显示了无限请求

我的React代码

class CityWeather extends Component {
  constructor(props){
    super(props)
    this.state = {
      city: "",
      temp: "",
      date: "Today"
    }
  }

  render() {
    const fetchWeatherData = location => {
        const url = 'http://api.openweathermap.org/data/2.5/forecast?q='+location+'&units=metric&APPID=65ea63d33ba78059603a85cba8c80620';
        fetch(url).then(res =>
          res.json()
        ).then(data => {
          this.setState({
            city: data.city.name,
            temp: data.list[0].main.temp
          })
        })
      }

    return (
      <div>
        {fetchWeatherData(this.props.name)}
        <div>{this.state.city}</div>
        <div>{this.state.date}</div>
        <div>{this.state.temp}</div>

      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:3)

每次渲染时,您都在获取天气数据。收到响应后,您可以通过setState更改组件的状态,这会导致重新渲染,从而导致无限循环。

也请参阅此帖子:what is right way to do API call in react js?

相反,在安装组件时,您应该获取天气数据,这只会发生一次。请参阅文档中的componentDidMount

class CityWeather extends Component {
    constructor(props){
        super(props)
        this.state = {
            city: "",
            temp: "",
            date: "Today"
        }
    }

    componentDidMount() {
        const fetchWeatherData = location => {
            const url = 'http://api.openweathermap.org/data/2.5/forecast?q='+location+'&units=metric&APPID=65ea63d33ba78059603a85cba8c80620';
            fetch(url)
                .then(res => res.json())
                .then(data => {
                    this.setState({
                        city: data.city.name,
                        temp: data.list[0].main.temp
                    })
                })
        };
        fetchWeatherData(this.props.name);
    }

    render() {
        return (
            <div>
                <div>{this.state.city}</div>
                <div>{this.state.date}</div>
                <div>{this.state.temp}</div>
            </div>
        )
    }
}