react之fetch請求json數據


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"}
]}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM