请求的方法一般放在生命周期的componentDidMount里
import React from 'react'
class RequestStu extends React.Component{
constructor(props){
super(props)
this.state={
test:{},
arr:[]
componentDidMount(){
fetch('http://localhost/console/scene/scenedetaillist',{
method:'GET',
headers:{
'Content-Type':'application/json;charset=UTF-8'
mode:'cors',
cache:'default'
.then(res =>res.json())
.then((data) => {
console.log(data)
this.setState({
test:data
},function(){
console.log(this.state.test)
let com = this.state.test.retBody.map((item,index)=>{
console.log(item.id)
return <li key={index}>{item.name}</li>
this.setState({
arr : com
},function(){
console.log(this.state.arr)
render(){
return (
this.state.arr
</div>
export default RequestStu
3.封装fetch请求
封装好方便调用
代码地址:github.com/klren0312/r…
const commonUrl = 'http://127.0.0.1:3456'
function parseJSON(response){
return response.json()
function checkStatus(response){
if(response.status >= 200 && response.status < 500){
return response
const error = new Error(response.statusText)
error.response = response
throw error
export default function request(options = {}){
const {data,url} = options
options = {...options}
options.mode = 'cors'
delete options.url
if(data){
delete options.data
options.body = JSON.stringify({
options.headers={
'Content-Type':'application/json'
return fetch(commonUrl+url,options,{credentials: 'include'})
.then(checkStatus)
.then(parseJSON)
.catch(err=>({err}))
使用封装好的请求
import React from 'react'
import request from './helper.js'
class RequestDemo extends React.Component{
componentDidMount(){
request({
url:'/posttest',
method:'post',
data:{"Header":{"AccessToken":"eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJzdWIiOiIxMDYiLCJleHBpciI6MTUxMDczODAzNjA5MiwiaXNzIjoiIn0.eo000vRNb_zQOibg_ndhlWbi27hPt3KaDwVk7lQiS5NJ4GS4esaaXxfoCbRc7-hjlyQ8tY_NZ24BTVLwUEoXlA"},"Body":{}}
}).then(function(res){
console.log(res)
render(){
return (
</div>
export default RequestDemo
NeoYu
React.js
- 4930
-
Java架构没有996
React.js
- 365
-
会煮咖啡的猫
React.js
Node.js
GitHub
- 1930
-
前端技术小哥
JavaScript
Promise