React---發送Ajax請求

1. 理解

1.1. 前置說明

  1. React本身只關注於界面, 並不包含發送ajax請求的代碼
  2. 前端應用需要通過ajax請求與後臺進行交互(json數據)
  3. react應用中需要集成第三方ajax庫(或自己封裝)
  4. jQuery: 比較重, 如果需要另外引入不建議使用
  5. axios: 輕量級, 建議使用

1.2. 常用的ajax請求庫

1) 封裝XmlHttpRequest對象的ajax

2)  promise風格

3) 可以用在瀏覽器端和node服務器端

2. axios

2.1. 文檔

  地址: https://github.com/axios/axios

   安裝axios: npm install axios

2.2. 相關API

  1)GET請求

 1 axios.get('/user?ID=12345')
 2   .then(function (response) {
 3     console.log(response.data);
 4   })
 5   .catch(function (error) {
 6     console.log(error);
 7   });
 8 
 9 axios.get('/user', {
10     params: {
11       ID: 12345
12     }
13   })
14   .then(function (response) {
15     console.log(response);
16   })
17   .catch(function (error) {
18     console.log(error);
19   });

2)POST請求

 1 axios.post('/user', {
 2   firstName: 'Fred',
 3   lastName: 'Flintstone'
 4 })
 5 .then(function (response) {
 6 console.log(response);
 7 })
 8 .catch(function (error) {
 9 console.log(error);
10 });

3. 案例

分析:

   1.設計狀態時要考慮全面,例如帶有網絡請求的組件,要考慮請求失敗怎麼辦。
        2.ES6小知識點:解構賦值+重命名
                    let obj = {a:{b:1}}
                    const {a} = obj; //傳統解構賦值
                    const {a:{b}} = obj; //連續解構賦值
                    const {a:{b:value}} = obj; //連續解構賦值+重命名
        3.消息訂閱與發佈機制
                    1.先訂閱,再發布(理解:有一種隔空對話的感覺)
                    2.適用於任意組件間通信
                    3.要在組件的componentWillUnmount取消訂閱
        4.fetch發送請求(關注分離的設計思想)
                    try {
                        const response= await fetch(`/api1/search/users?q=${keyWord}`)
                        const data = await response.json()
                        console.log(data);
                    } catch (error) {
                        console.log('請求出錯',error);
                    }

(1)App.jsx

 1 import React, { Component } from 'react'
 2 import Search from './components/Search'
 3 import List from './components/List'
 4 
 5 export default class App extends Component {
 6 
 7     state = { //初始化狀態
 8         users:[], //users初始值爲數組
 9         isFirst:true, //是否爲第一次打開頁面
10         isLoading:false,//標識是否處於加載中
11         err:'',//存儲請求相關的錯誤信息
12     } 
13 
14     //更新App的state
15     updateAppState = (stateObj)=>{
16         this.setState(stateObj)
17     }
18 
19     render() {
20         return (
21             <div className="container">
22                 <Search updateAppState={this.updateAppState}/>
23                 <List {...this.state}/>
24             </div>
25         )
26     }
27 }

(2) List.jsx

 1 import React, { Component } from 'react'
 2 import './index.css'
 3 
 4 export default class List extends Component {
 5     render() {
 6         const {users,isFirst,isLoading,err} = this.props
 7         return (
 8             <div className="row">
 9                 {
10                     isFirst ? <h2>歡迎使用,輸入關鍵字,隨後點擊搜索</h2> :
11                     isLoading ? <h2>Loading......</h2> :
12                     err ? <h2 style={{color:'red'}}>{err}</h2> :
13                     users.map((userObj)=>{
14                         return (
15                             <div key={userObj.id} className="card">
16                                 <a rel="noreferrer" href={userObj.html_url} target="_blank">
17                                     <img alt="head_portrait" src={userObj.avatar_url} style={{width:'100px'}}/>
18                                 </a>
19                                 <p className="card-text">{userObj.login}</p>
20                             </div>
21                         )
22                     })
23                 }
24             </div>
25         )
26     }
27 }

(3) Search.jsx

 1 import React, { Component } from 'react'
 2 import axios from 'axios'
 3 
 4 export default class Search extends Component {
 5 
 6     search = ()=>{
 7         //獲取用戶的輸入(連續解構賦值+重命名)
 8         const {keyWordElement:{value:keyWord}} = this
 9         //發送請求前通知App更新狀態
10         this.props.updateAppState({isFirst:false,isLoading:true})
11         //發送網絡請求
12         axios.get(`/api1/search/users?q=${keyWord}`).then(
13             response => {
14                 //請求成功後通知App更新狀態
15                 this.props.updateAppState({isLoading:false,users:response.data.items})
16             },
17             error => {
18                 //請求失敗後通知App更新狀態
19                 this.props.updateAppState({isLoading:false,err:error.message})
20             }
21         )
22     }
23 
24     render() {
25         return (
26             <section className="jumbotron">
27                 <h3 className="jumbotron-heading">搜索github用戶</h3>
28                 <div>
29                     <input ref={c => this.keyWordElement = c} type="text" placeholder="輸入關鍵詞點擊搜索"/>&nbsp;
30                     <button onClick={this.search}>搜索</button>
31                 </div>
32             </section>
33         )
34     }
35 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章