持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天,点击查看活动详情
安装jquery
安装jquery
在cmd中进入React文件夹,输入npm install jquery+(版本号) -D
在在webpack.conflg.js头部加入:
var webpack = require('webpack');
在webpack.conflg.js末尾加入:
plugins: [new webpack.IgnorePlugin(/\.\/jquery-last.js$/),//排除不想打包进去的插件
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})]
在使用jquery的组件头部加入:
var $=require('jquery');
fetch插件
Fetch API是一种新规范,用来取代XMLHttpRequest对象。它主要有两个特点:
一:接口合理化,Ajax是将所有不同性质的接口都放在XHR对象上,而Fetch是将他们分散在几个不同的对象上,设计更加合理
二:'Fetch操作返回Promise对象,避免了嵌套的回调函数'
语法:fetch(url,obj)
url:请求地址,obj为设置参数(json对象格式)
obj为设置参数(json对象格式)包含以下内容:
method:请求使用方法。get或post
headers:请求头信息,形式为Headers的对象或包含ByteString值的对象字面量
body:请求body信息:可能是一个Blob、BufferSource(二进制)、FormData(表单数据)、
URLSearchParams或者USVString对象。
注:get或head方法的请求不能包含body信息
mode:请求的模式。如:cors(跨域)、no-cors或者same-origin(同域)
cache(缓存):请求cache模式:default、no-store、reload、no-cache、force-cache或者only-if-cached
credentials:请求credentials,如omit、same-origin或者include。为了在当前域名内自动发送cookie,
必须提供这个选项,从Chrome 50 开始,这个属性也可以接受FederatedCredential实例或是一个PasswordCredential实例
'redirect:可用的redirect模式:follow(自动重定向),error(如果产生重定向将自动终止并且抛出一个错误)
或者manual(手动处理重定向)。在谷歌浏览器中,74之前是默认的'
referrer:一个USVString,可以是一个no-referrer、client或者一个URL。默认是client
'上面诸多option中,其实常用的就是method、headers、body以及mode等'
header设置:
可以为Headers对象,也可以是一个对象字面量,通常情况下对象字面量就足够
实例:
headers:new Headers({
'Content-Type':'application/json'
})
或常用的
headers:{
"Content-Type":"application/x-www-form-urlencoded"
}
response
response(传给then的回调函数可以接收一个参数,这个参数就是Response,它的属性基本上是只读属性)用法如下:
Response.clone():创建一个Response对象的克隆
Response.error():返回一个绑定了网络错误的新Response对象
'Response.redirect():用另一个URL创建一个新的response'
'Response.json():读取Response对象并且将它设置为已读(因为Response对象被设置为了stream的方式,
所以他们只能被读取一次),并返回一个解析为json格式的promise对象'
'Response.text():读取Response对象并且将它设置为已读(因为Response对象被设置为了stream的方式,
所以他们只能被读取一次),并返回一个被解析为USVString格式的promise对象'
Response.arrayBuffer():读取Response对象并且将它设置为已读(因为Response对象被设置为了stream的方式,
所以他们只能被读取一次)并返回一个被解析为ArrayBuffer格式的promise对象
Response.blob():读取Response对象并且将它设置为已读(因为Response对象被设置为了stream的方式,
所以他们只能被读取一次)并返回一个被解析为Blob格式的promise对象
Response。formData():读取Response对象并且将它设置为已读(因为Response对象被设置为了stream的方式,
所以他们只能被读取一次)并返回一个被解析为FormData格式的promise对象
fetch实例
import React from 'react';
export class Fetch extends React.Component {
constructor() {
super();
this.state = { tes: [], tesshow: false };
}
getteah() {
fetch('URl', {
method: 'post',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'username=csgo&userpwd=12345678&userclass=74&type=2',
}).then((v) => {
return v.json()
}).then((ts) => {
for (let i in ts) {
this.state.tes.push(ts[i]);
}
this.setState({ tes: this.state.tes, tesshow: true });
})
}
componentDidMount() {
this.getteah();
}
render() {
return (
<div>
{!this.state.tesshow ? "数据加载中..." : this.state.tes.map((v, i) => {
return (
<div key={i}>{v.name_coach}
<p>{v.id_coach}</p>
<img src={'url' + v.path_coach} />
</div>)
})}
</div>
)
}
}