search
HomeWeb Front-endFront-end Q&AHow to request data with react fetch
How to request data with react fetchJan 05, 2023 am 10:02 AM
reactfetch

React fetch request data method: 1. Place the requested method in the "componentDidMount" of the life cycle; 2. Encapsulate the fetch request; 3. Pass "function checkStatus(response){...}" Method to check the request status; 4. Use the encapsulated request and print the result on the server or browser.

How to request data with react fetch

#The operating environment of this tutorial: Windows 10 system, react16 version, Dell G3 computer.

How does react fetch request data?

React Fetch request

I need to use it recently, so learn it

1.fetch

Promise-based ajax Request

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API

2. React uses fetch

The request method is generally put In componentDidMount of the life cycle

Basic format of requested data

How to request data with react fetch

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 (
      <div>
       <ul>
          {
            this.state.arr
          }
       </ul>
      </div>
    )
  }
}
export default RequestStu

Displayed after request:

How to request data with react fetch

3. Encapsulate fetch request

Encapsulate it for easy calling

Code address: https://github.com/klren0312/react_study/blob/master/stu13/src/helper.js

helper.js

//全局路径
const commonUrl = &#39;http://127.0.0.1:3456&#39;
//解析json
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 = &#39;cors&#39;//跨域
  delete options.url
  if(data){
    delete options.data
    options.body = JSON.stringify({
      data
    })
  }
  options.headers={
    &#39;Content-Type&#39;:&#39;application/json&#39;
  }
  return fetch(commonUrl+url,options,{credentials: &#39;include&#39;})
    .then(checkStatus)
    .then(parseJSON)
    .catch(err=>({err}))
}

Use encapsulated requests

import React from &#39;react&#39;
import request from &#39;./helper.js&#39;
class RequestDemo extends React.Component{
  componentDidMount(){
    request({
      url:&#39;/posttest&#39;,
      method:&#39;post&#39;,
      data:{"Header":{"AccessToken":"eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJzdWIiOiIxMDYiLCJleHBpciI6MTUxMDczODAzNjA5MiwiaXNzIjoiIn0.eo000vRNb_zQOibg_ndhlWbi27hPt3KaDwVk7lQiS5NJ4GS4esaaXxfoCbRc7-hjlyQ8tY_NZ24BTVLwUEoXlA"},"Body":{}}
    }).then(function(res){
      console.log(res)
    })
  }
  render(){
    return (
      <div>
    test
      </div>
    )
  }
}
export default RequestDemo

Server printing

How to request data with react fetch

Browser printing

How to request data with react fetch

Comes with a bonus helper class

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
}
/**
 * 登录请求
 * 
 * @param data 数据
 */
export function loginReq(data){ 
  const options = {}
  options.method = &#39;post&#39;
  options.made = &#39;cors&#39;
  options.body = JSON.stringify(data)
  options.headers={
    &#39;Content-Type&#39;:&#39;application/json&#39;
  }
  return fetch(&#39;/loginOk&#39;,{ ...options, credentials:&#39;include&#39;})
    .then(checkStatus)
    .then(parseJSON)
    .then((res)=>{
      if(res.retCode === &#39;0001&#39;){
        localStorage.setItem(&#39;x-access-token&#39;,res.retBody.AccessToken)
        return &#39;success&#39;
      }
      else if(res.retCode === &#39;0002&#39;){
        return &#39;error&#39;
      }
      else if(res.retCode === &#39;0003&#39;){
        return &#39;error&#39;
      }else{
        return ;
      }
      
    })
    .catch(err=>({err}))
}
/**
 * 普通请求
 * @param {*url,*method,*data} options 
 */
export  function request(options = {}){
  const Authorization = localStorage.getItem(&#39;x-access-token&#39;)
  const {data,url} = options
  options = {...options}
  options.mode = &#39;cors&#39;
  delete options.url
  if(data){
    delete options.data
    options.body = JSON.stringify(data)
  }
  options.headers={
    &#39;x-access-token&#39;:Authorization,
    &#39;Content-Type&#39;:&#39;application/json;charset=UTF-8&#39;
  }
  return fetch(url,{ ...options, credentials: &#39;include&#39;})
    .then(checkStatus)
    .then(parseJSON)
    .catch(err=>({err}))
}

Recommended learning: "react video tutorial"

The above is the detailed content of How to request data with react fetch. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
在Vue应用中使用axios时出现“TypeError: Failed to fetch”怎么办?在Vue应用中使用axios时出现“TypeError: Failed to fetch”怎么办?Jun 24, 2023 pm 11:03 PM

最近,在使用Vue应用开发过程中,我遇到了一个常见的问题:“TypeError:Failedtofetch”错误提示。这个问题出现在使用axios进行HTTP请求时,后端服务器没有正确响应请求时发生。这种错误提示通常表明请求无法到达服务器,可能是由于网络原因或服务器未响应造成的。出现这个错误提示后,我们应该怎么办呢?以下是一些解决方法:检查网络连接由于

react中antd和dva是什么意思react中antd和dva是什么意思Apr 21, 2022 pm 03:25 PM

在react中,antd是基于Ant Design的React UI组件库,主要用于研发企业级中后台产品;dva是一个基于redux和“redux-saga”的数据流方案,内置了“react-router”和fetch,可理解为应用框架。

React是双向数据流吗React是双向数据流吗Apr 21, 2022 am 11:18 AM

React不是双向数据流,而是单向数据流。单向数据流是指数据在某个节点被改动后,只会影响一个方向上的其他节点;React中的表现就是数据主要通过props从父节点传递到子节点,若父级的某个props改变了,React会重渲染所有子节点。

react中为什么使用nodereact中为什么使用nodeApr 21, 2022 am 10:34 AM

因为在react中需要利用到webpack,而webpack依赖nodejs;webpack是一个模块打包机,在执行打包压缩的时候是依赖nodejs的,没有nodejs就不能使用webpack,所以react需要使用nodejs。

react中forceupdate的用法是什么react中forceupdate的用法是什么Apr 19, 2022 pm 12:03 PM

在react中,forceupdate()用于强制使组件跳过shouldComponentUpdate(),直接调用render(),可以触发组件的正常生命周期方法,语法为“component.forceUpdate(callback)”。

react是组件化开发吗react是组件化开发吗Apr 22, 2022 am 10:44 AM

react是组件化开发;组件化是React的核心思想,可以开发出一个个独立可复用的小组件来构造应用,任何的应用都会被抽象成一颗组件树,组件化开发也就是将一个页面拆分成一个个小的功能模块,每个功能完成自己这部分独立功能。

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

react和reactdom有什么区别react和reactdom有什么区别Apr 27, 2022 am 10:26 AM

react和reactdom的区别是:ReactDom只做和浏览器或DOM相关的操作,例如“ReactDOM.findDOMNode()”操作;而react负责除浏览器和DOM以外的相关操作,ReactDom是React的一部分。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!