一、前期说明
前置说明:
1.React本身只关注与界面,并不包含发送ajax请求的代码
2.前端应用需要通过ajax请求与后台交互(json数据)
3.react应用中需要集成第三方库或自己封装
常用的ajax请求库
1.jquery:比较重,如果需要另外引入不建议使用
2.axio:轻量级,建议使用
(1)封装XmlHttpRequest对象的ajax
(2)promise风格
(3)可以用在浏览器端和node服务器端
二、axios
1.使用的服务器是通过node+express搭建起来的:(需要装express包)
// service1.js
const express = require('express');
const app = express()
app.use((request, response, next) => {
console.log('有人请求服务器1');
next()
})
app.get('/students', (request,response) => {
const students = [
{id: '001',name: 'tom', age:10},
{id: '002',name: 'jeery', age:19},
{id: '003',name: 'tony', age:20},
]
response.send(students)
})
app.listen(5000, (err) => {
if(!err) console.log('服务器1启动成功了,请求学生信息为:http://localhost:5000/students')
})
// service2.js
const express = require('express');
const app = express()
app.use((request, response, next) => {
console.log('有人请求服务器2');
next()
})
app.get('/cars', (request,response) => {
const cars = [
{id: '001',name: '奔驰', age:199},
{id: '002',name: '马白达', age:109},
{id: '003',name: '捷达', age: 120},
]
response.send(cars)
})
app.listen(5001, (err) => {
if(!err) console.log('服务器2启动成功了,请求汽车信息为:http://localhost:5001/cars')
})
app.js中的源码:
import './App.css';
import React, {Component} from 'react'
import axios from 'axios'
// 创建并暴露App组件
class App extends Component{
getStudentData = () => {
axios.get('http://localhost:3000/api1/students').then((response) => {
console.log('成功了', response.data);
},
error => {console.log('失败了')}
)}
getCarData = () => {
axios.get('http://localhost:3000/api2/cars').then((response) => {
console.log('成功了', response.data);
},
error => {console.log('失败了')}
)}
render() {
return (
<div>
<button onClick={this.getStudentData}>点我获取学生数据</button>
<button onClick={this.getCarData}>点我获取汽车数据</button>
</div>
)
}
}
export default App;
配置代理的文件在下方展示
2.在使用过程中会遇到跨域问题
(1)解决方法1:
在package.json文件中加入一行代码:
"proxy": "http://localhost:5000"
说明:
1>优点:配置清单,前端请求资源时可以不加任何事情
2>缺点:不能配置多个代理
3>工作方式:上述方式配置代理,当请求了3000不存在的资源时,那么该请求会转发给5000(优先匹配前端资源)
(2)解决办法2:
在src下建一个setupProxy.js文件
具体代码如下:
// commonJs的语法,因为不是给前端代码人员执行的,他是脚手架会找到这个文件加到webpack配置中
const {createProxyMiddleware} = require('http-proxy-middleware')
module.exports = function(app) {
app.use(
createProxyMiddleware('/api1', { // 遇见/api1前缀的请求,就会触发该代理配置
target: 'http://localhost:5000', // 请求转发给谁,配置转发的目标地址(能返回数据的服务器地址)
changeOrigin: true, // 控制服务器收到的响应头中Host字段的值
/*
changeOrigin为true时,服务器收到的请求头中的host为:localhost:5000
changeOrigin为false时,服务器收到的请求头中的host为:localhost:3000
changeOrigin默认值为false,但我们一般将changeOrigin设置为true
*/
pathRewrite: {// 重写请求路径(必须),去除请求前缀,保证交给后台服务器的是正常请求地址
'^/api1': ''
}
}),
createProxyMiddleware('/api2', {
target: 'http://localhost:5001',
changeOrigin: true,
pathRewrite: {
'^/api2': ''
}
})
)
}
说明:
1>优点:可以配置对个代理,可以灵活的控制请求是否走代理
2>缺点:配置繁琐,前端请求资源时必须加前缀
三、关于axios的一个案例
搜索案例:主要是两个模块Search、List模块
未配置代理,因为本地没有部署的服务器,所以直接使用的原地址。
1.此方法是将状态数据放在App里使用的父子通信,以及子父通信的方法传递数据
// App.js
import React, { Component } from 'react'
import Search from './components/Search'
import List from './components/List'
export default class App extends Component {
state = {
users: [], // 初始化状态
isFirst: true, // 是否为第一次打开页面
isLoading: false, // 标识是都处于加载中
err: '' // 存储请求相关的错误信息
}
updateAppState =(stateObj) => {
console.log(stateObj);
this.setState(stateObj)
}
render() {
return (
<div>
<Search updateAppState={this.updateAppState}/>
<List {...this.state}/>
</div>
)
}
}
// Search.js
import React, { Component } from 'react'
import axios from 'axios'
export default class Search extends Component {
search = () => {
// 获取用户的输入(连续结构复制+重命名)
const { keyWordElement: {value:keyWord} } = this
console.log(keyWord);
// 发送请求前通知App更新状态
this.props.updateAppState({
isFirst:false,
isLoading: true
})
// 发送网络请求https://api.github.com/search/users?q=111
axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
(response)=> {
// 请求成功后通知App更新状态
this.props.updateAppState({isLoading: false,users:response.data.items})
},
(error) => {
this.props.updateAppState({isLoading: false, err:error.message})
}
)
}
render() {
return (
<div>
<section>
<h3>搜索github用户</h3>
<div style={{'marginBottom': '15px'}}>
<input ref={c => this.keyWordElement = c} type="text" placeholder='输入关键词点击搜索'/>
<button onClick={this.search}>搜索</button>
</div>
</section>
</div>
)
}
}
// List.js
import React, { Component } from 'react'
import './index.css'
export default class List extends Component {
render() {
const {users, isLoading, isFirst, err} = this.props
return (
<div className='row'>
{
isFirst ? <h2>欢迎使用,输入关键字,随后点击搜索</h2>:
isLoading? <h2>Loading...</h2>:
err? <h2 style={{'color': 'red'}}>{err}</h2>:
users.map((userObj) => {
return (
<div key={userObj.id}>
<a rel="noreferrer" href={userObj.html_url} target='blank'>
<img src={userObj.avatar_url} alt='head_portrait' style={{width:'100px'}}/>
</a>
<p>{userObj.login}</p>
</div>
)
})
}
</div>
)
}
}
// List中的index.css
.row {
display: flex;
width: 500px;
align-items: flex-start;
justify-content: space-between;
flex-wrap: wrap;
}
2.使用兄弟间通信
// App.js
import React, { Component } from 'react'
import Search from './components/Search'
import List from './components/List'
export default class App extends Component {
render() {
return (
<div>
<Search/>
<List/>
</div>
)
}
}
// Search.jsx
import React, { Component } from 'react'
import axios from 'axios'
import Pubsub from 'pubsub-js'
export default class Search extends Component {
search = () => {
Pubsub.publish('guyu', {name: 'tom', age: '10'})
// 获取用户的输入(连续结构复制+重命名)
const { keyWordElement: {value:keyWord} } = this
console.log(keyWord);
// 发送请求前通知List更新状态
/*this.props.updateAppState({
isFirst:false,
isLoading: true
})*/
Pubsub.publish('guyu',{
isFirst:false,
isLoading: true
})
// 发送网络请求https://api.github.com/search/users?q=111
axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
(response)=> {
// 请求成功后通知List更新状态
/*this.props.updateAppState({isLoading: false,users:response.data.items})*/
Pubsub.publish('guyu',{isLoading: false,users:response.data.items})
},
(error) => {
Pubsub.publish('guyu',{isLoading: false, err:error.message})
// this.props.updateAppState({isLoading: false, err:error.message})
}
)
}
render() {
return (
<div>
<section>
<h3>搜索github用户</h3>
<div style={{'marginBottom': '15px'}}>
<input ref={c => this.keyWordElement = c} type="text" placeholder='输入关键词点击搜索'/>
<button onClick={this.search}>搜索</button>
</div>
</section>
</div>
)
}
}
// List.jsx
import React, { Component } from 'react'
import Pubsub from 'pubsub-js'
import './index.css'
export default class List extends Component {
state = {
users: [], // 初始化状态
isFirst: true, // 是否为第一次打开页面
isLoading: false, // 标识是都处于加载中
err: '' // 存储请求相关的错误信息
}
componentDidMount() {
this.token = Pubsub.subscribe('guyu', (_,stateObj) => {
this.setState(stateObj)
})
}
componentWillUnmount() {
Pubsub.unsubscribe(this.token)
}
render() {
const {users, isLoading, isFirst, err} = this.state
return (
<div className='row'>
{
isFirst ? <h2>欢迎使用,输入关键字,随后点击搜索</h2>:
isLoading? <h2>Loading...</h2>:
err? <h2 style={{'color': 'red'}}>{err}</h2>:
users.map((userObj) => {
return (
<div key={userObj.id}>
<a rel="noreferrer" href={userObj.html_url} target='blank'>
<img src={userObj.avatar_url} alt='head_portrait' style={{width:'100px'}}/>
</a>
<p>{userObj.login}</p>
</div>
)
})
}
</div>
)
}
}
3.以上使用的都是基于XHR发起请求,除了用此发请求,还可以使用Fetct内置的方式发起请求:
与第2点相比,只是Search组件的请求方法中有变更,如有需要,将以下代码在请求方法search()中更新一下即可。
// 发送网络请求,fetch方法(未优化前的)
fetch(`https://api.github.com/search/users?q=${keyWord}`).then(
(response) =>{
console.log('联系服务器成功了');
return response.json()
},
(error) => {
console.log('联系服务器失败了', error);
return new Promise()
}
).then(
response => {
console.log('获取数据成功了', response);
},
error => {
console.log('获取数据失败了', error);
}
)
// 发送网络请求,fetch方法(优化后的)
try {
const response = await fetch(`https://api.github.com/search/users?q=${keyWord}`)
const data = await response.json()
Pubsub.publish('guyu',{isLoading: false,users:data.items})
} catch(error) {
Pubsub.publish('guyu',{isLoading: false, err:error.message})
}
4.此案例的知识点总结
1>设计状态时要考虑全面,例如常有带有网络请求的组件,要考虑请求失败怎么办
2>Es6小知识点,解构赋值+重命名
let obj = {a: {b:1}}
const {a} = obj // 传统结构赋值
const {a: {b}} = obj // 连续解构赋值
const {a: {b: value}} = value // 连续解构赋值+重命名
3>消息订阅与发布机制
(1)先订阅,再发布(理解:有一种隔空对话的机制)
(2)适用于任意组件间通信
(3)要在组件的componentWillUnmount中取消订阅
4>fetch发送请求(关注分离的设计思想),相关在第3点中已经详细说明。