生活随笔
收集整理的這篇文章主要介紹了
Fetch发送网络请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 文檔
https://github.github.io/fetch/ https://segmentfault.com/a/1190000003810652
2. 特點
fetch: 原生函數,不再使用XmlHttpRequest對象提交ajax請求 老版本瀏覽器可能不支持
3. 相關API
GET請求
fetch ( url
) . then ( function ( response ) { return response
. json ( ) } ) . then ( function ( data ) { console
. log ( data
) } ) . catch ( function ( e ) { console
. log ( e
) } ) ;
POST請求
fetch ( url
, { method
: "POST" , body
: JSON . stringify ( data
) , } ) . then ( function ( data ) { console
. log ( data
) } ) . catch ( function ( e ) { console
. log ( e
) } )
import React
, { Component
} from 'react' ;
import PubSub
from 'pubsub-js'
import axios
from "axios" ; class Search extends Component { search = async ( ) => { const { keyWordElement
: { value
: keyword
} } = this PubSub
. publish ( 'zep' , { isFirst
: false , isLoading
: true } ) fetch ( ` https://api.github.com/search/users?q= ${ keyword} ` ) . then ( ( response ) => { console
. log ( '聯系服務器成功了' ) return response
. json ( ) } ) . then ( ( response ) => { console
. log ( '獲取數據成功' , response
) } ) . catch ( ( error ) => { console
. log ( '請求出錯' , error
) } ) } render ( ) { return ( < section className
= "jumbotron" style
= { { textAlign
: "center" } } > < h3 className
= "jumbotron-heading" > 搜索github用戶
< / h3
> < div
> < input ref
= { c => this . keyWordElement
= c
} type
= "text" placeholder
= "輸入關鍵詞點擊搜索" / > & nbsp
; < button onClick
= { this . search
} > 搜索
< / button
> < / div
> < / section
> ) ; }
} export default Search
;
4.1. 總結
設計狀態時要考慮全面,例如帶有網絡請求的組件,要考慮請求失敗怎么辦。
ES6小知識點:解構賦值+重命名 let obj = {a:{b:1}} const {a} = obj; //傳統解構賦值 const {a:{b}} = obj; //連續解構賦值 const {a:{b:value}} = obj; //連續解構賦值+重命名
消息訂閱與發布機制 1.先訂閱,再發布(理解:有一種隔空對話的感覺) 2.適用于任意組件間通信 3.要在組件的componentWillUnmount中取消訂閱
fetch發送請求(關注分離的設計思想)
try { const response
= await fetch ( ` /api1/search/users2?q= ${ keyWord} ` ) const data
= await response
. json ( ) console
. log ( data
) ; } catch ( error
) { console
. log ( '請求出錯' , error
) ; }
總結
以上是生活随笔 為你收集整理的Fetch发送网络请求 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。