web端三大框架react、vue和angular,本篇教程介绍react的从入门到精通。
如何在 React 中发起 AJAX 请求?
在 React 开发中,你能使用任何你喜欢的 AJAX 库,比如社区比较流行的 Axios,jQuery AJAX,或者是浏览器内置的 window.fetch。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items });
},
// 注意:需要在此处处理错误
// 而不是使用 catch() 去捕获错误
// 因为使用 catch 去捕获异常会掩盖掉组件本身可能产生的 bug
(error) => {
this.setState({
isLoaded: true,
error });
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading…</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}}
官方给出的是fetch发出的请求,但是追梦猪是从vue过来的所以喜欢axios请求,不过你也可以使用普通的jquery的$.ajax请求这样都是被允许的
当然也可以使用ajax的方法进行数据交互
$.ajax({
type: "POST",
url:"此处填url地址",
contentType: "application/json; charset=utf-8",
data: JSON.stringify("此处填header请求头"),
dataType: "json",
success: function (message){
}
})
如果你是axios请求的爱好者使用如下:
文档目录
config.js存放公共的url请求路径
index.js封装的请求暴露文件
request.js存放axios的请求拦截和响应拦截
config.js代码如下;
/
统一定义接口,有利于维护
/
const URL= 'https://app.kpcx179.com/' ;//开发环境
export default URL
根据自己需求定义请求的地址
request.js代码如下:
import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
axios.interceptors.request.use(//请求参数设置
config => {
console.log(config)
if (localStorage.getItem('token')&&localStorage.getItem('token')!==undefined&&localStorage.getItem('token')!=='') {
config.headers.common['token'] = localStorage.getItem('token');
}else{
window.location.href='/#/login'
}
return config
},
err => {
return Promise.reject(err)
})
axios.interceptors.response.use(//响应请求
config => {
console.log(config)
if (config.data.code==101046) {
window.location.href='/#/login'
}else{
if (localStorage.getItem('token')&&localStorage.getItem('token')!==undefined&&localStorage.getItem('token')!=='') {
localStorage.setItem('token', config.headers.token);
}
}
return config
},
err => {
return Promise.reject(err)
})
export default axios
index.js代码如下:
import React from 'react';
import request from './request';
import config from './config';
let axios = {
get(url, params, headers) {
let options = {};
params && (options.params = params);
headers && (options.headers = headers);
return request.get(config+url, options);
},
post(url, params, headers) {
let options = {};
headers && (options.headers = headers);
return request.post(config+url, params, options);
}
}
React.$http = axios
在react脚手架创建的项目中,类似像axios请求这样的公共方法,需要给它设定到一个全局的方法中。|
对比vue,vue可以直接在main.js中直接Vue.prototype.$axios = function(){}这样的形式绑定全局的方法。这样就不用每一个vue文件都去引用axios这个文件了,也方便进行统一的管理。
那么react是不是也可以类似的在index.js中react.prototype绑定全局方法呢。答案是不行!!!
分析
直接在index.js中打印
console.log(React.prototype)
//undefined
和vue不一样,vue需要将vue new成对象才能使用并且每个vue文件直接通过this就能获取到vue对象上定义的东西。但是react不需要new成对象就可以直接使用。
方法
直接在index.js中
React.$axios = function () {}
绑定方法;然后每个子页面的js文件中React.$http 直接获取到这个方法
封装的方法如下图:
效果图如下:
如果你对上面的一无所知的话可以访问追梦猪git下载demo实现快捷开发,省掉安装的步骤
追梦猪react项目demo实例(https://github.com/jiawenguang/React-demo.git)
可以通过git clone方式下载项目结构。
本文地址:https://www.zhuimengzhu.com/details/224.html
转载地址:暂无
转载说明:转载时请在文首注明来源zhuimengzhu.com 及教程作者,并附本文链接。谢谢各位编辑同仁配合。zhuimengzhu 保留追究相应责任的权利。