【React学习】React中如何发送请求?

1. axios安装

在React中,我们选择axios发送请求。
axios的安装,在项目终端里输入:npm install axios
package.json文件中查看是否安装成功
【React学习】React中如何发送请求?_第1张图片

2. 使用axios请求高德地图天气查询数据

创建Weather.jsx组件

import React, { Component } from 'react'
import axios from "axios"

export default class Hello extends Component {
    constructor(){
        super()
        this.state={
            weather:{}
        }
    }
	
	// 使用axios发送get请求获取数据
    getData=()=>{
        axios.get("https://restapi.amap.com/v3/weather/weatherInfo",{
            params:{
            	// 要在高德地图API中申请自己的key值
                key:"输入你自己的key值",
                city:"宁波"
            }
        }).then((res)=>{
            console.log(res)
            this.setState({
                weather:res.data.lives[0]
            })
        })
    }

    componentDidMount(){
        this.getData()
    }

    render() {
    	// 解构赋值
        const{city,weather,temperature}=this.state.weather
        return (
            <div>
                <h1>{city}的天气是{weather},温度是{temperature}</h1>
            </div>
        )
    }
}

App.js文件中渲染Weather.jsx组件

import Weather from "./Weather"
import React, { Component } from 'react'

class App extends Component {
  render() {
    return (
        <div>
          <h1>高德地图天气查询API</h1>
          <Weather/>
        </div>
    )
  }
}

export default App;

3. 效果

【React学习】React中如何发送请求?_第2张图片

你可能感兴趣的:(前端学习,#,React学习,前端,react.js)