React本身只关注于界面, 并不包含发送ajax请求的代码,前端应用需要通过ajax请求与后台进行交互(json数据),可以使用集成第三方ajax库(或自己封装)

常用的ajax请求库

jQuery: 比较重, 如果需要另外引入不建议使用

axios: 轻量级, 建议使用,封装XmlHttpRequest对象的ajax,promise风格,可以用在浏览器端和node服务器端

fetch: 原生函数, 但老版本浏览器不支持,不再使用XmlHttpRequest对象提交ajax请求,为了兼容低版本的浏览器, 可以引入兼容库fetch.js

常用的ajax请求库—axios

相关API—get请求

axios.get('/user?ID=12345').then(function (response) {

console.log(response);

}) .catch(function (error) {

console.log(error);

});

axios.get('/user', {

params: {

ID: 12345

}

}).then(function (response) {

console.log(response);

}).catch(function (error) {

console.log(error);

});

相关API—post请求

axios.post('/user', {

firstName: 'Fred',

lastName: 'Flintstone'

}).then(function (response) {

console.log(response);

}).catch(function (error) {

console.log(error);

});

常用的ajax请求库—fetch

由于 Fetch API 是基于 Promise 设计,有必要先学习一下 Promise,推荐阅读 MDN Promise 教程。旧浏览器不支持 Promise,需要使用 polyfill es6-promise

Fetch API 很简单,看文档很快就学会了。推荐 MDN Fetch 教程 和 万能的WHATWG Fetch 规范

相关API-get请求

fetch(url).then(function(response) {

return response.json()

}).then(function(data) {

console.log(data)

}).catch(function(e) {

console.log(e)

});

相关API-post请求

fetch(url, {

method: "POST",

body: JSON.stringify(data),

}).then(function(data) {

console.log(data)

}).catch(function(e) {

console.log(e)

})

分别使用axios和fetch实现一个搜索案例

效果大致如下

使用脚手架创建项目并且创建目录结构并且编写静态的组件

将这个功能抽出来一整个模块(search),将主组件在App.js中引入

search.js(主组件)

组件中需要接收子组件search-input.js传过来的一个searchName数据,search组件拿到这个数据进行请求后台,将返回的数据传递给子组件search-list

search-list有四个状态,初始(initView),查询中(loading),查询的数据(users),查询失败信息(errorMsg),在父组件中传递给子组件search-list并且根据查询结果进行更新这四个状态,更新状态后子组件会接收到最新的状态

先来看看使用axios

import React, {Component} from 'react'

import axios from 'axios'

import './search.css';

import SearchInput from './search-input/search-input'

import SearchList from './search-list/search-list'

class Search extends Component {

// search-list有四个状态,初始(initView),查询中(loading),查询的数据(users),查询失败信息(errorMsg)

state = {

initView: true,

loading: false,

users: [],

errorMsg: ''

}

search = (searchName) => {

const url = `https://api.github.com/search/users?q=${searchName}`

this.setState({ initView: false, loading: true })

axios.get(url)

.then((response) => {

this.setState({ loading: false, users: response.data.items })

})

.catch((error) => {

console.log('error', error.response.data.message, error.message)

this.setState({ loading: false, errorMsg: error.message })

})

}

render() {

const {initView, loading, users, errorMsg} = this.state

return (

)

}

}

export default Search

.search-axios{

width: 900px;

height: 600px;

margin: 40px auto 0;

border: 1px solid #cccccc;

box-sizing: border-box;

}

.search-input-cantain{

width: 100%;

height: 100px;

padding: 20px;

box-sizing: border-box;

border-bottom: 1px solid #cccccc;

}

.search-list-cantain{

width: 100%;

height: 500px;

padding: 20px;

box-sizing: border-box;

}

子组件search-input

将输入框的数据使用自定义事件传个父组件search

import React, {Component} from 'react'

import './search-input.css';

import propTypes from 'prop-types'

class SearchInput extends Component {

static propTypes = {

search: propTypes.func.isRequired

}

handleSearch = () => {

// 获取输入框中的数据

const searchName = this.searchName.value

// 更新状态

this.props.search(searchName)

// 清空输入框中的数据

this.searchName.value = ''

}

render() {

return (

this.searchName = input} placeholder='enter the name you search'/>

Search

)

}

}

export default SearchInput

.search-input input{

width: 80%;

height: 35px;

border-bottom-left-radius: 4px;

border-top-left-radius: 4px;

outline: none;

border: 1px solid #cccccc;

padding: 0 8px;

box-sizing: border-box;

}

.search-input button{

width: 20%;

text-align: center;

height: 35px;

line-height: 35px;

outline: none;

border: 1px solid #cccccc;

box-sizing: border-box;

cursor: pointer;

vertical-align: -2px;

border-bottom-right-radius: 4px;

border-top-right-radius: 4px;

}

子组件search-list根据父组件search传过来的四个状态进行判断显示

import React, {Component} from 'react'

import './search-list.css';

import propTypes from "prop-types";

class SearchList extends Component {

static propTypes = {

initView: propTypes.bool.isRequired,

loading: propTypes.bool.isRequired,

users: propTypes.array.isRequired,

errorMsg: propTypes.string.isRequired

}

render() {

const {initView, loading, users, errorMsg} = this.props

if (initView) {

return

enter the name you search

} else if (loading) {

return

搜索中,请稍后.....

} else if (errorMsg) {

return

{errorMsg}

} else {

return (

{users.map((user, index) => (

{user.login}

))}

)

}

}

}

export default SearchList

.search-list{

width: 100%;

height: 460px;

overflow-y: auto;

}

.search-item{

width: 25%;

height: 150px;

display: inline-block;

padding: 10px;

box-sizing: border-box;

}

.search-item-img{

width: 70%;

margin: 0 auto;

text-align: center;

}

.search-item-img img{

max-width: 100%;

}

.search-item p{

width: 100%;

text-align: center;

margin:;

padding:;

}

.search-hide-enter,.search-ing,.search-error{

font-size: 20px;

}

另外一种方式是子组件search-input将输入框的数据使用自定义事件传个父组件search,父组件search在将这个数据传个子组件search-list,子组件search-list接收到新的属性时自动调用componentWillReceiveProps这个方法继续ajax请求

search组件

import React, {Component} from 'react'

import './search.css';

import SearchInput from './search-input/search-input'

import SearchList from './search-list/search-list'

class Search extends Component {

state = {

searchName: ''

}

search = (searchName) => {

this.setState({searchName})

}

render() {

const {searchName} = this.state

return (

)

}

}

export default Search

search-list组件

import React, {Component} from 'react'

import './search-list.css';

import propTypes from "prop-types";

import axios from 'axios'

class SearchList extends Component {

static propTypes = {

searchName: propTypes.string.isRequired

}

state = {

initView: true,

loading: false,

users: [],

errorMsg: null

}

// 当组件接收到新的属性时回调(生命周期的函数)

async componentWillReceiveProps(newProps) {

const {searchName} = newProps

const url = `https://api.github.com/search/users?q=${searchName}`

this.setState({ initView: false, loading: true })

try {

let data = await axios.get(url);

this.setState({ loading: false, users: data.data.items })

} catch(e) {

this.setState({ loading: false, errorMsg: e.message })

console.log("Oops, error", e);

}

}

render() {

const {initView, loading, users, errorMsg} = this.state

if (initView) {

return

enter the name you search

} else if (loading) {

return

搜索中,请稍后.....

} else if (errorMsg) {

return

{errorMsg}

} else {

return (

{users.map((user, index) => (

{user.login}

))}

)

}

}

}

export default SearchList

最终效果

[Web 前端] 如何在React中做Ajax 请求?

cp from : https://segmentfault.com/a/1190000007564792 如何在React中做Ajax 请求? 首先:React本身没有独有的获取数据的方式.实际上, ...

React 中的 AJAX 请求:获取数据的方法

React 中的 AJAX 请求:获取数据的方法 React 只是使用 props 和 state 两处的数据进行组件渲染. 因此,想要使用来自服务端的数据,必须将数据放入组件的 props 或 st ...

Vue中发送ajax请求——axios使用详解

axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用 功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 htt ...

React中的Ajax

React中的Ajax 组件的数据来源,通常是通过Ajax请求从服务器获取,可以使用componentDidMount方法设置Ajax请求,等到请求成功,再用this.setState方法重新渲染UI ...

PHP--------TP中的ajax请求

PHP--------TP中的ajax请求 以jQuery中的ajax为例: (1)引入jQuery 通过模板替换表示路径,我们可以自定义模板替换变量(在config中定义) /*自定义模板替换标签* ...

javascrpt 中的Ajax请求

回顾下javascript中的Ajax请求,写一个小例子: ...

ASP.NET Core Razor中处理Ajax请求

如何ASP.NET Core Razor中处理Ajax请求 在ASP.NET Core Razor(以下简称Razor)刚出来的时候,看了一下官方的文档,一直没怎么用过.今天闲来无事,准备用Rozor ...

HighCharts中的Ajax请求的2D折线图

HighCharts中的Ajax请求的2D折线图 设计源码:

关于JQuery中的ajax请求或者post请求的回调方法中的操作执行或者变量修改没反映的问题

前段时间做一个项目,而项目中所有的请求都要用jquery 中的ajax请求或者post请求,但是开始处理一些简单操作还好,但是自己写了一些验证就出现问题了,比如表单提交的时候,要验证帐号的唯一性,所以 ...

随机推荐

Hadoop学习笔记—12.MapReduce中的常见算法

一.MapReduce中有哪些常见算法 (1)经典之王:单词计数 这个是MapReduce的经典案例,经典的不能再经典了! (2)数据去重 "数据去重"主要是为了掌握和利用并行化思 ...

[ubuntu14.04 amd64 ]搜狗拼音輸入法安裝

这个网址下载之后,双击下载的deb文件http://mirrors.sohu.com/deepin/pool/non-free/f/fcitx-sogoupinyin-release/ 就会在ubun ...

动态规划——H 最少回文串

We say a sequence of characters is a palindrome if it is the same written forwards and backwards. Fo ...

sso单点登录解决方案收集

本文来自:http://blog.csdn.net/huwei2003/article/details/6038017 我的想法是使用集中验证方式,多个站点集中Passport验证. 主站:Passp ...

打印杨辉三角--for循环

要求打印7行直角杨辉三角 杨辉三角特点: 第1行和第2行数字都为1: 从第三行开始,除去开头和结尾数字为1,中间数字为上一行斜对角两个数字的和. 如下图: 打印结果: 代码如下: package 杨辉 ...

maven编译时错误:无效的目标发行版

(转)Maven 将依赖打进一个jar包 博客分类: maven   maven配置 <?xml version="1.0" encoding="UTF-8&quo ...

bzoj 3566&colon; &lbrack;SHOI2014&rsqb;概率充电器

Description 著名的电子产品品牌 SHOI 刚刚发布了引领世界潮流的下一代电子产品--概率充电器:"采用全新纳米级加工技术,实现元件与导线能否通电完全由真随机数决定!SHOI 概率 ...

【前端】Angular2 Ionic2 学习记录

转载请注明出处:http://www.cnblogs.com/shamoyuu/p/angular2_ionic2.html 一.建立项目 ionic start ProductName super ...

项目文件与 SVN 资源库同步提示错误 Attempted to lock an already-locked dir

问题描述 之前为了图方便,在eclipse中直接把三个jsp文件复制到了eclipse中我新建的一个文件夹中,把svn版本号信息也带过来了,然后我又删除了这三个jsp文件,接着先把这三个jsp复制到桌 ...

【Asia Yokohama Regional Contest 2018】Arithmetic Progressions

题目大意:给定 N(1

react 使用ajax axios,react中使用Ajax请求(axios,Fetch)相关推荐

  1. 【Ajax】了解Ajax与jQuery中的Ajax

    一.了解Ajax 什么是Ajax Ajax 的全称是 Asynchronous Javascript And XML(异步 JavaScript 和 XML). 通俗的理解:在网页中利用 XMLHtt ...

  2. ajax引入html_Vue中发送ajax请求的库有哪些?

    一.vue-resource 在Vue中实现异步加载需要使用到vue-resource库,利用该库发送ajax(Vue官方已不再维护这个库). 1.引入vue-resource:<script ...

  3. vue使用ajax库,Vue 中使用Ajax请求

    Vue 项目中常用的 2 个 ajax 库 (一)vue-resource vue 插件, 非官方库,vue1.x 使用广泛 vue-resource 的使用 在线文档   https://githu ...

  4. sweetalert 2.0 ajax,处理SweetAlert2中的AJAX返回值

    我使用带有AJAX请求的SweetAlert2 Popup.一旦用户点击提交,我执行请求. 在PHP文件中,我对提交的数据进行了一些验证,根据结果,我想在SweetAlert2中为用户提供反馈作为信息 ...

  5. asp接收ajax乱码_Asp中处理AJAX乱码问题总结

    AJAX中的这样写法: XMLHttpReq.open('get',"getsubcategory.asp?BigClassName="+BigClassName+"&a ...

  6. php中ajax用法,thinkphp中使用ajax

    前端页面请求表单,接收返回值 ~~~ function aa() { $.get("{:u('Userspay/test')}",function(data,status) { / ...

  7. html ajax输出表格中,使用Ajax来渲染HTML表格

    其实我有一个PHP代码,这使得一台 StageREQUESTREPLY foreach($allinfool as $infool){ print(" "); print(&quo ...

  8. vuex ajax dev,vuex中使用ajax的话如何维护状态?

    例如,我在初始化状态的时候,在action里面写了一个函数异步去获取初始化数据然后初始化vuex的状态,但是这样子的话我在组件里面就获取不了这个状态了,代码: actions export const ...

  9. vue可以用ajax,Vue 中使用Ajax请求

    Vue 项目中常用的 2 个 ajax 库 (一)vue-resource vue 插件, 非官方库,vue1.x 使用广泛 vue-resource 的使用 下载 npm install vue-r ...

  10. jQuery框架学习第六天:jQuery中的Ajax应用

    一.摘要 本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案,  即使你会使用jQuery也能在阅读中发现些许秘籍. 本篇文章讲解如何使用jQuery方便快捷的实现A ...

最新文章

  1. C指针5:字符串指针(指向字符串的指针)
  2. 巴克码信号处理的计算机仿真,巴克码信号处理的计算机仿真
  3. 数据库系统概念总结:第十一章 索引与散列
  4. PHP错误处理 - debug_backtrace()的用法
  5. IT项目管理的十六个字心得体会
  6. C++ multiset
  7. 分析MySQL数据类型的长度
  8. python如何循环执行_如何在python中多次运行for循环?
  9. ege管理系统_网上人才管理系统方案
  10. python ORM 模块peewee(三): Model的建立
  11. 计算机网络与Netty - F2F
  12. 细思极恐的星座分析(下)- 外太空?内子宫?人类的天赋从何而来?
  13. BAT、网易面试经验收集
  14. Apache漏洞汇总:
  15. CC BY-SA 4.0知识共享许可协议
  16. Android lunch分析以及产品分支构建
  17. delphi 企业微信消息机器人_企业微信群消息机器人发送开源项目
  18. 深入学习java源码之Math.max()与 Math.min()
  19. DSSS|直接系列扩频技术
  20. 中兴智能视觉大数据研发人脸识别门禁考勤机、精准的人脸识别对比

热门文章

  1. macd ema java源码_[转载]彩色MACD指标源码
  2. python怎样控制继电器_使用Python和树莓派控制跨阵M2继电器通断
  3. C语言基础入门:C-Free5新建C语言工程
  4. uniapp小程序根据经纬度精确定位
  5. 世界上最神奇的网站收录--不是最无聊就是最有意思
  6. 【延展Extension的使用场景 Objective-C语言】
  7. speedoffice表格如何根据身份证号计算年龄
  8. laravel excel 导出图片
  9. HDU - How far away ?(DFS+vector)
  10. 什么是软件测试?简介,基础知识和重要性