react后端請求數據如何實現

本篇內容主要講解“react后端請求數據如何實現”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“react后端請求數據如何實現”吧!

網站設計制作、成都網站建設介紹好的網站是理念、設計和技術的結合。創(chuàng)新互聯(lián)公司擁有的網站設計理念、多方位的設計風格、經驗豐富的設計團隊。提供PC端+手機端網站建設,用營銷思維進行網站設計、采用先進技術開源代碼、注重用戶體驗與SEO基礎,將技術與創(chuàng)意整合到網站之中,以契合客戶的方式做到創(chuàng)意性的視覺化效果。

react后端請求數據的實現方法:1、在package.json中配置“ "proxy":"http://localhost:5000"”;2、在src目錄下創(chuàng)建“setupProxy.js”文件;3、調用“setupProxy.js”中配置的功能,代碼如“createProxyMiddleware('/api2',{target:...}”。

react-ajax請求后臺數據方法

react-ajax

axios

方法一:在package.json中配置

 "proxy":"http://localhost:5000"
  • 這樣localhost:5000就是我們要代理到的服務器

  getStudentData = () => {
   axios.get('/students').then(
     (result) => { console.log(result.data); },
     (reason) => { console.log(reason); })
 }
  • 獲取localhost:5000中/students的數據

優(yōu)點:**配置簡單,前端請求資源不需要任何前綴

缺點:**不能配置多個代理服務器

方法二:在src目錄下創(chuàng)建setupProxy.js文件

  • 第一步:webpack配置了調用setupProxy.js中配置的功能

  • setupProxy.js

  • 第二步:配置

  • //const proxy=require("http-proxy-middleware")   :視頻中請求的包,引用它出現了無法訪問的問題//應該使用以下寫法*******const { createProxyMiddleware } = require("http-proxy-middleware");module.exports=function(app){
       app.use(
           createProxyMiddleware('/api1',{//遇見/api1前綴的請求,就會觸發(fā)該代理配置
               target:"http://localhost:5000",//請求轉發(fā)給誰
               changeOrigin:true,//控制服務器收到的請求頭中Host字段的值:host就是主機名+端口號
                //true:后端接收到的host:localhost:5000
                //false:后端接收到的host:localhost:3000
                //系統(tǒng)默認為false,一般會設為true
               pathRewrite:{"^/api1":""}//重寫請求路徑(必須要寫)
               //不寫:后臺接收到的請求路徑:/api1/student
               //寫了:后臺請求的路徑:/student
           }),
           createProxyMiddleware('/api2',{
               target:"http://localhost:5001",
               changeOrigin:true,
               pathRewrite:{"^/api2":""}
           }),
       )}

跨域請求真實接口案例
  • App.jsx

  • import React, { Component } from 'react'
    import Search from './components/Search'
    import List from './components/List'
    import './App.css'

    export default class App extends Component {
    state={users:[]}
    getSearchResult=(result)=>{
     this.setState({users:result})
    }

     render() {
       return (
         <div className="container">
           <Search getSearchResult={this.getSearchResult}/>
           <List users={this.state.users}/>
         </div>
       )
     }
    }

  • Search.jsx

  • import React, { Component } from 'react'
    import axios from 'axios'
    import './index.css'

    export default class Search extends Component {

     search = () => {
       //獲取輸入框中的值
       const { value } = this.keyWordElement;
       //發(fā)送請求
       axios.get(`/api1/search/users?q=${value}`).then(
         result => {
           this.props.getSearchResult(result.data.items)
         },
         reason => {
           console.log(reason);
         })
     }



     render() {
       return (
         <section className="jumbotron">
           <h4 className="jumbotron-heading">搜索github用戶</h4>
           <div>
             <input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search" />&nbsp;<button onClick={this.search}>搜索</button>
           </div>
         </section>
       )
     }
    }

  • List.jsx

import React, { Component } from 'react'

import './index.css'
export default class List extends Component {
 render() {
   return (
     <div className="row">
       {this.props.users.map(item=>{
           return    <div key={item.id} className="card">
               <a href={item.html_url} target="_blank">
                 <img src={item.avatar_url} style={{ width: "100px" }} />
               </a>
               <p className="card-text">{item.login}</p>
             </div>
       })}
 
     
     </div>  
   )
 }
}

react-任意組件間的通信

消息訂閱與發(fā)布機制

PubSubJs:

  • pub:(publish)發(fā)布

  • sub:(subscribe)訂閱

pubsub-js:就是用來實現發(fā)布訂閱的,可以把它看過vue中的eventBus,看作是函數的載體

  • 訂閱方:創(chuàng)建一個函數,并且將這個函數傳給pubsub做托管

    • var token=PubSub.subscribe("myTopic",myFunction[托管的函數])//token,是當前訂閱函數的唯一id,可以用來取消訂閱

  • 發(fā)布方:發(fā)布的意思就是通過調用訂閱方指定的函數,實現傳參或執(zhí)行操作功能

    • PubSub.publish('myTopic','需要發(fā)送給訂閱者的內容')

第一步:添加pubsub-js

  • yarn add pubsub-js

**第二步:**在組件中導入

  • import PubSub from 'pubsub-js'

**第三步:**調用PubSub訂閱函數(一般是在componentDidMount鉤子函數中訂閱)

  •   componentDidMount(){
       this.token=PubSub.subscribe("changeState",this.changeStateObj)
     }

demo

List.jsx

import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './index.css'
export default class List extends Component {
 state={
   users:[],//拿到的用戶信息
   isFirst:true,//是否第一次訪問
   isLoading:false,//是否正在加載
   err:"",//返回的錯誤信息
 
 }

 changeStateObj=(msg,value)=>{
   this.setState(value)
 }

 componentDidMount(){
   this.token=PubSub.subscribe("changeState",this.changeStateObj)
 }
 componentWillUnmount(){
   PubSub.unsubscribe(this.token)
 }

 render() {
   let {users,isFirst,isLoading,err}=this.state
   return (
     <div className="row">
       {
         isFirst?<h3>輸入搜索內容搜索用戶</h3>:
         isLoading?<h3>Loading...</h3>:
         err?<h3>{err}</h3>:
       
         users.map(item=>{
           return    <div key={item.id} className="card">
               <a href={item.html_url} target="_blank">
                 <img src={item.avatar_url} style={{ width: "100px" }} />
               </a>
               <p className="card-text">{item.login}</p>
             </div>
       })}
 
     
     </div>  
   )
 }
}

Search.jsx

import React, { Component } from 'react'
import axios from 'axios'
import './index.css'
import PubSub from 'pubsub-js'

export default class Search extends Component {
 

 search = () => {
   //獲取輸入框中的值
   const { value } = this.keyWordElement;
   PubSub.publish('changeState',{isFirst:false,isLoading:true})
   //發(fā)送請求
   axios.get(`/api1/search/users2?q=${value}`).then(
     result => {
       PubSub.publish('changeState',{isLoading:false,users:result.data.items})

     },
     reason => {
       PubSub.publish('changeState',{isLoading:false,err:reason.message})

     })
 }



 render() {
   return (
     <section className="jumbotron">
       <h4 className="jumbotron-heading">搜索github用戶</h4>
       <div>
         <input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search" />&nbsp;<button onClick={this.search}>搜索</button>
       </div>
     </section>
   )
 }
}

App.jsx

import React, { Component } from 'react'
import Search from './components/Search'
import List from './components/List'
import './App.css'

export default class App extends Component {



 render() {
   return (
     <div className="container">
       <Search />
       <List/>
     </div>
   )
 }
}

發(fā)送ajax請求的方式有哪些?

  • xhr:xmlHttpRequest:傳統(tǒng)的ajax

    • jQuery:封裝了xhr

    • axios:封裝了xhr

  • **fetch(取來)?*window內置的,不用借用第三方庫,直接使用

    • 缺點:目前不是很好用,沒有請求發(fā)送攔截器

xhr

react后端請求數據如何實現

fetch

  • 缺點:兼容性不高

  • 優(yōu)點:沒有用xhr,不用安裝第三方庫,原生

react后端請求數據如何實現

fetch最優(yōu)寫法
let getData=async()=>{	
try{
       let result=await fetch(url);
       let data=await result.json();
   }catch(error){
       console.log('請求錯誤',error)
   }
}

到此,相信大家對“react后端請求數據如何實現”有了更深的了解,不妨來實際操作一番吧!這里是創(chuàng)新互聯(lián)網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

網站欄目:react后端請求數據如何實現
文章URL:http://www.muchs.cn/article36/gjggpg.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供網站內鏈、做網站電子商務、網頁設計公司自適應網站、靜態(tài)網站

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)