Fetch下载
npm install whatwg-fetch -S
Fetch请求json数据
json文件要放在public内部才能被检索到
具体实现
创建一个fetch.js组件
import React,{Component} from 'react'
import 'whatwg-fetch'
class Fetch extends Component{
constructor(props){
super(props)
this.state={
datas:[]
}
this.getData=this.getData.bind(this)
}
getData(){
fetch('../client/data.json')
.then(response=>response.json())
.then(data=>{this.setState({datas:data.arr})})
.catch(e=>{console.log("error")})
}
render(){
const datas=this.state.datas;
return (
<div>
<button onClick={this.getData.bind(this)}>我是</button>
<ul>
{ datas.map((item,index)=>{
return <li key={index}>{item.names}</li>
})}
</ul>
</div>
)
}
}
export default Fetch;
本地json文件
{"arr":[ {"city":"hebei","names":"chenbin"}, {"city":"nanyang","names":"xuexue"}, {"city":"beijing","names":"dongge"}]}