站長(zhǎng)資訊網(wǎng)
        最全最豐富的資訊網(wǎng)站

        react后端請(qǐng)求數(shù)據(jù)怎么實(shí)現(xiàn)

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

        react后端請(qǐng)求數(shù)據(jù)怎么實(shí)現(xiàn)

        本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。

        react后端請(qǐng)求數(shù)據(jù)怎么實(shí)現(xiàn)?

        react-ajax請(qǐng)求后臺(tái)數(shù)據(jù)方法

        react-ajax

        axios

        方法一:在package.json中配置

         "proxy":"http://localhost:5000"
        登錄后復(fù)制

        • 這樣localhost:5000就是我們要代理到的服務(wù)器

          getStudentData = () => {     axios.get('/students').then(       (result) => { console.log(result.data); },       (reason) => { console.log(reason); })   }
        登錄后復(fù)制

        • 獲取localhost:5000中/students的數(shù)據(jù)

        **優(yōu)點(diǎn):**配置簡(jiǎn)單,前端請(qǐng)求資源不需要任何前綴

        **缺點(diǎn):**不能配置多個(gè)代理服務(wù)器

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

        • 第一步:webpack配置了調(diào)用setupProxy.js中配置的功能

        • setupProxy.js

        • 第二步:配置

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

        • 解決問題鏈接:https://www.csdn.net/tags/OtTaIg0sNzE3OC1ibG9n.html

        跨域請(qǐng)求真實(shí)接口案例

        • 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>     )   } }
          登錄后復(fù)制

        • 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ā)送請(qǐng)求     axios.get(`/api1/search/users?q=${value}`).then(       result => {         this.props.getSearchResult(result.data.items)       },       reason => {         console.log(reason);       })   }      render() {     return (       <section className="jumbotron">         <h3 className="jumbotron-heading">搜索github用戶</h3>         <div>           <input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search" />&nbsp;<button onClick={this.search}>搜索</button>         </div>       </section>     )   } }
          登錄后復(fù)制

        • 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>       )   } }
        登錄后復(fù)制

        react-任意組件間的通信

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

        PubSubJs:

        • pub:(publish)發(fā)布
        • sub:(subscribe)訂閱

        pubsub-js:就是用來(lái)實(shí)現(xiàn)發(fā)布訂閱的,可以把它看過(guò)vue中的eventBus,看作是函數(shù)的載體

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

          • var token=PubSub.subscribe("myTopic",myFunction[托管的函數(shù)])//token,是當(dāng)前訂閱函數(shù)的唯一id,可以用來(lái)取消訂閱
            登錄后復(fù)制

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

          • PubSub.publish('myTopic','需要發(fā)送給訂閱者的內(nèi)容')
            登錄后復(fù)制

        第一步:添加pubsub-js

        • yarn add pubsub-js
          登錄后復(fù)制

        **第二步:**在組件中導(dǎo)入

        • import PubSub from 'pubsub-js'
          登錄后復(fù)制

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

        •   componentDidMount(){     this.token=PubSub.subscribe("changeState",this.changeStateObj)   }
          登錄后復(fù)制

        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:"",//返回的錯(cuò)誤信息      }    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?<h2>輸入搜索內(nèi)容搜索用戶</h2>:           isLoading?<h2>Loading...</h2>:           err?<h2>{err}</h2>:                    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>       )   } }
        登錄后復(fù)制

        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ā)送請(qǐng)求     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">         <h3 className="jumbotron-heading">搜索github用戶</h3>         <div>           <input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search" />&nbsp;<button onClick={this.search}>搜索</button>         </div>       </section>     )   } }
        登錄后復(fù)制

        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ù)制

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

        • xhr:xmlHttpRequest:傳統(tǒng)的ajax
          • jQuery:封裝了xhr
          • axios:封裝了xhr
        • **fetch(取來(lái))?*window內(nèi)置的,不用借用第三方庫(kù),直接使用
          • 缺點(diǎn):目前不是很好用,沒有請(qǐng)求發(fā)送攔截器

        xhr

        react后端請(qǐng)求數(shù)據(jù)怎么實(shí)現(xiàn)

        fetch

        • 缺點(diǎn):兼容性不高
        • 優(yōu)點(diǎn):沒有用xhr,不用安裝第三方庫(kù),原生

        react后端請(qǐng)求數(shù)據(jù)怎么實(shí)現(xiàn)

        fetch最優(yōu)寫法

        let getData=async()=>{	 	try{         let result=await fetch(url);         let data=await result.json();     }catch(error){         console.log('請(qǐng)求錯(cuò)誤',error)     } }
        登錄后復(fù)制

        推薦學(xué)習(xí):《react視頻教程》

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)
        主站蜘蛛池模板: 欧美精品一区二区精品久久 | 国产精品久久久久天天影视| 精品人妻一区二区三区毛片| 国产原创精品视频| 亚洲一区爱区精品无码| 久久99精品久久久久久9蜜桃| 久久久精品免费国产四虎| 久久久久人妻一区精品性色av| 青草青草久热精品视频在线观看| 91精品日韩人妻无码久久不卡| 国产亚洲精品岁国产微拍精品| 亚洲精品视频免费| 男女男精品网站免费观看| 国产午夜精品一本在线观看 | 精品人妻系列无码天堂| 无码AV动漫精品一区二区免费| 国产精品制服丝袜亚洲欧美| 一区二区三区四区精品视频| 国产亚洲综合成人91精品| 国产精品国色综合久久| 久久久久女人精品毛片| 亚洲精品中文字幕乱码三区| 无码国产亚洲日韩国精品视频一区二区三区 | 欧美日韩国产精品系列| 国产三级精品久久| 国产在线精品观看免费观看| 国产精品香蕉在线观看| 国产精品 码ls字幕影视| 2021国产成人精品久久| 欧美精品亚洲精品日韩1818| 欧美精品免费在线| 四虎国产精品永久地址49| 热久久国产精品| 国产va免费精品| 国产精品人人做人人爽人人添| 98香蕉草草视频在线精品看 | 欧美精品亚洲精品日韩| 亚洲欧美日韩精品永久在线| 99热亚洲精品6码| 国产精品自在在线午夜福利 | 久久成人国产精品二三区|