日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

React網(wǎng)絡(luò)請(qǐng)求發(fā)起方法詳細(xì)介紹_React

作者:月光曬了很涼快 ? 更新時(shí)間: 2022-11-18 編程語(yǔ)言

1. 發(fā)起網(wǎng)絡(luò)請(qǐng)求

首先需要安裝 axios 庫(kù):

yarn add axios

發(fā)起網(wǎng)絡(luò)請(qǐng)求:

import React, { Component } from 'react'
import { get } from './utils/http'
import Loading from './components/Loading'
class App extends Component {
  state = {
    users: null
  }
  async componentDidMount() {
    let users = await get('/mock/users.json')
    this.setState({ users })
  }
  render() {
    return (
      <div>
        {
          // 條件渲染
          // 第一次執(zhí)行過來(lái)是null,防止報(bào)錯(cuò)就需要加一個(gè)判斷
          this.state.users ? <h3>{this.state.users.name}</h3> : <Loading />
        }
      </div>
    )
  }
}
export default App

mock 數(shù)據(jù):

{
  "id": 1,
  "name": "張三"
}

2. 開發(fā)時(shí)網(wǎng)絡(luò)請(qǐng)求代理配置

使用create-react-app來(lái)創(chuàng)建的react工程,如果有請(qǐng)求跨域,在開發(fā)時(shí)的解決方案首先需要新建配置文件 src/setupProxy.js文件,并通過 yarn 安裝 http-proxy-middleware,代理中間件模塊:

yarn add -D http-proxy-middleware

setupProxy.js:

// 此文件是create-react-app創(chuàng)建的工程提供的一個(gè)代理網(wǎng)絡(luò)請(qǐng)求文件入口
// 此文件給nodejs調(diào)用,模塊化要使用commonjs
// 修改此文件需要重啟項(xiàng)目
// 實(shí)現(xiàn)代理需要安裝 代理中間件模塊 yarn add -D http-proxy-middleware
const { createProxyMiddleware: proxy } = require('http-proxy-middleware')
const userMockFn = require('../mock/user')
// // 內(nèi)置了express
module.exports = app => {
  userMockFn(app)
  // 參數(shù)1:以什么規(guī)則開頭
  app.use('/api', proxy({
    // 目標(biāo)地址
    target: 'https://api.iynn.cn/film',
    // 修改主機(jī)頭
    changeOrigin: true
  }))
}

App.jsx:

import React, { Component } from 'react'
import { get } from './utils/http'
import Loading from './components/Loading'
class App extends Component {
  state = {
    users: null
  }
  async componentDidMount() {
    let users = await get('/api/v1/getNowPlayingFilmList?cityId=110100&pageNum=1&pageSize=10')
    console.log(users)
  }
  render() {
    return (
      <div>
        {
          // 條件渲染
          // 第一次執(zhí)行過來(lái)是null,防止報(bào)錯(cuò)就需要加一個(gè)判斷
          this.state.users ? <h3>{this.state.users.name}</h3> : <Loading />
        }
      </div>
    )
  }
}
export default App

原文鏈接:https://blog.csdn.net/weixin_45605541/article/details/127024561

欄目分類
最近更新