React网络请求fetch之get请求
本文介绍下React下fetch的get使用步骤
参考文章网络请求之fetch
(1)编写基础组件模板

根组件引入


(2)json-server搭建模拟后台服务
编写模拟数据

自定义端口启动

测试如下

(3)结合生命周期componentDidMount进行fetch网络请求操作


注意:fetch后的then的response不是最终结果,可以测试下


返回的response为流数据,需要用response.json()进行转换,而该方法返回Promise对象,所以后续便有了类似then调用,结合文章网络请求之fetch.上述代码还可以做下完善如下

接下来覆盖state初始值并进行模板渲染即可
(4)覆盖state初始状态并渲染


完整代码如下:
import React,{Component} from 'react'
class FetchGet extends Component {
constructor(props){
super(props)
this.state = {
usersInfo:[]
}
}
componentDidMount(){
fetch('http://localhost:2222/users')
.then((response)=>{
return response.json()
})
.then((response)=>{
this.setState({
usersInfo:response
})
}).catch((error)=>{
console.log('错误'+error)
})
}
render(){
var {usersInfo} = this.state//解构赋值
return (
<div>
<ul>
{
usersInfo.map((item,index)=>{
return (
<li key={index}>
{item.id}
{item.username}
{item.age}
</li>
)
})
}
</ul>
</div>
)
}
}
export default FetchGet

(5)细节点
1、尽量使用箭头函数,因为箭头函数没有特定this指向
2、箭头函数只有一个参数时,()可以省略,所以上诉代码如下

3、采用ES2016的 async/await 语法进行进一步优化
详见下面
(6)采用ES2016的 async/await 语法优化
对比如下

此外在做下优化
因为response.json()也是异步的所以也需要await

完整代码:
import React,{Component} from 'react'
class FetchGet extends Component {
constructor(props){
super(props)
this.state = {
usersInfo:[]
}
}
componentDidMount(){
;(async()=>{
try{
const response = await fetch('http://localhost:2222/users')
const data = await response.json()//因为也是异步的所以也需要await
this.setState({
usersInfo:data
})
}catch(error){
console.log('Fetch Error: ', error)
}
})()
/*
fetch('http://localhost:2222/users')
.then(response => {
return response.json()
})
.then(response => {
this.setState({
usersInfo:response
})
}).catch(error => {
console.log('错误'+error)
})
*/
}
render(){
var {usersInfo} = this.state//解构赋值
return (
<div>
<ul>
{
usersInfo.map((item,index)=>{
return (
<li key={index}>
{item.id}
{item.username}
{item.age}
</li>
)
})
}
</ul>
</div>
)
}
}
export default FetchGet
.

浙公网安备 33010602011771号