2022-04-05
React
0
请注意,本文编写于 1178 天前,最后修改于 517 天前,其中某些信息可能已经过时。

目录

写在前面
脚手架配置代理
方法一
方法二
gitee搜索用户案例
静态组件
axios发送请求
展示数据
优化展示
消息订阅与发布
fetch发送请求
总结

写在前面

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

常用的ajax请求库

  • jQuery:比较重,如果需要另外引入不建议使用
  • axios:轻量级,建议使用
    • npm i axios
    • 封装XmlHttpRequest对象的ajax
    • promise风格
    • 可以用在浏览器端和node服务器端

启动server.js服务

server1.js

js
const express = require('express') const app = express() app.use((request,response,next)=>{ console.log('有人请求服务器1了'); console.log('请求来自于',request.get('Host')); console.log('请求的地址',request.url); next() }) app.get('/students',(request,response)=>{ const students = [ {id:'001',name:'tom',age:18}, {id:'002',name:'jerry',age:19}, {id:'003',name:'tony',age:120}, ] response.send(students) }) app.listen(5000,(err)=>{ if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students'); })

server2.js

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:'奔驰',price:199}, {id:'002',name:'马自达',price:109}, {id:'003',name:'捷达',price:120}, ] response.send(cars) }) app.listen(5001,(err)=>{ if(!err) console.log('服务器2启动成功了,请求汽车信息地址为:http://localhost:5001/cars'); })

脚手架配置代理

直接发送请求时会跨域,需要为脚手架配置代理(跨域时请求可发出,服务器可接收,但客户端无法接收返回的信息)

方法一

package.json中追加配置:"proxy": "http://localhost:5000",,请求时直接请求项目地址。

  1. 优点:配置简单,前端请求资源时可以不加任何前缀。
  2. 缺点:不能配置多个代理。
  3. 工作方式:上述方式配置代理,当请求了3000不存在的资源时,那么该请求会转发给5000 (优先匹配前端资源)。

方法二

src目录下创建配置文件:src/setupProxy.js

  1. 优点:可以配置多个代理,可以灵活的控制请求是否走代理。
  2. 缺点:配置繁琐,前端请求资源时必须加前缀。
js
// commonJS写法,不能用ES6写法 const {createProxyMiddleware} = require('http-proxy-middleware') module.exports = function(app) { app.use( createProxyMiddleware('/api1', { //api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000) 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': ''} }) ) }

gitee搜索用户案例

image.png

静态组件

App.jsx

jsx
import React, { Component } from 'react' import List from './components/List' import Search from './components/Search' export default class App extends Component { render() { return ( <div className="container"> <Search /> <List /> </div> ) } }

components/Search/index.jsx

jsx
import React, { Component } from 'react' export default class Search extends Component { render() { return ( <section className="jumbotron"> <h3 className="jumbotron-heading">搜索Gitee用户</h3> <div> <input type="text" placeholder="键入想要搜索的内容"/>&nbsp;<button>搜索</button> </div> </section> ) } }

components/List/index.jsx

jsx
import React, { Component } from 'react' import './index.css' export default class List extends Component { render() { return ( <div className="row"> <div className="card"> <a rel="noreferrer" href="https://github.com/reactjs" target="_blank"> <img alt="name" src="https://avatars.githubusercontent.com/u/6412038?v=3" style={{width: '100px'}}/> </a> <p className="card-text">reactjs</p> </div> </div> ) } }

components/List/index.css

css
.album { min-height: 50rem; /* Can be removed; just added for demo purposes */ padding-top: 3rem; padding-bottom: 3rem; background-color: #f7f7f7; } .card { float: left; width: 33.333%; padding: .75rem; margin-bottom: 2rem; border: 1px solid #efefef; text-align: center; } .card>img { margin-bottom: .75rem; border-radius: 100px; } .card-text { font-size: 85%; }

axios发送请求

请求地址:https://gitee.com/api/v5/search/users?q=xxxxx

据天禹老师所讲,请求过于频繁可能会401,因此提供了一个本地的服务器用于存放一部分数据以保证项目的顺利展示,这里就不写了

jsx
export default class Search extends Component { searchUser = () => { // 获取用户的输入 const {keyWordElement: {value: keyWord}} = this // 解构赋值的连续写法 + 重命名 // 发送网络请求 axios.get(`https://gitee.com/api/v5/search/users?q=${keyWord}`).then( value => { console.log('success', value.data) }, reason => { console.log('fail', reason) } ) } render() { return ( <section className="jumbotron"> <h3 className="jumbotron-heading">搜索Gitee用户</h3> <div> <input ref={c => this.keyWordElement = c} type="text" placeholder="键入想要搜索的内容"/>&nbsp; <button onClick={this.searchUser}>搜索</button> </div> </section> ) } }

解构赋值与连续解构赋值:

js
let obj = {a: {b: {c: 1}}} let obj2 = {a: {b: 1}} console.log('@', obj.a.b.c) const {a: {b: {c}}} = obj console.log('#', c) const {a: {b: data}} = obj2 console.log('$', data)

image.png

展示数据

App组件接收用户数据并传递给List组件

jsx
export default class App extends Component { state = {users: []} // 初始化状态,users初始值为数组 saveUsers = (users) => { this.setState({users}) } render() { return ( <div className="container"> <Search saveUsers={this.saveUsers}/> <List users={this.state.users}/> </div> ) } }

List组件展示数据

jsx
export default class List extends Component { render() { return ( <div className="row"> { this.props.users.map((userObj) => { return ( <div key={userObj.id} className="card"> <a rel="noreferrer" href={userObj.html_url} target="_blank"> <img alt={userObj.name} src={userObj.avatar_url==='https://gitee.com/assets/no_portrait.png' ? 'https://avatars.githubusercontent.com/u/6412038?v=3' : userObj.avatar_url + '!avatar200'} style={{width: '100px'}}/> </a> <p className="card-text">{userObj.login}</p> </div> ) }) } </div> ) } }

GIF 2022-4-13 18-09-24.gif

优化展示

App.jsx

jsx
import React, { Component } from 'react' import List from './components/List' import Search from './components/Search' export default class App extends Component { state = { // 初始化状态 users: [], // users初始值为数组 isFirst: true, // 是否首次打开页面 isLoading: false, // 是否加载中 err: '' // 存储请求错误 } // 更新App的state updateAppState = (stateObj) => { this.setState(stateObj) } /*saveUsers = (users) => { this.setState({users}) } changeIsFirst = (users) => { this.setState({users}) } changeIsLoading = (users) => { this.setState({users}) } saveErr = (users) => { this.setState({users}) }*/ render() { return ( <div className="container"> <Search updateAppState={this.updateAppState}/> <List {...this.state}/> </div> ) } }

components/Search/index.jsx

jsx
import React, { Component } from 'react' import axios from 'axios' export default class Search extends Component { searchUser = () => { // 获取用户的输入 const {keyWordElement: {value: keyWord}} = this // 解构赋值的连续写法 + 重命名 // 发送请求前通知App更新状态 this.props.updateAppState({isFirst: false, isLoading: true}) // 发送网络请求 axios.get(`https://gitee.com/api/v5/search/users?q=${keyWord}`).then( value => { // 请求成功后通知App更新状态 this.props.updateAppState({isLoading: false, users: value.data}) }, reason => { // 请求失败后通知App更新状态 this.props.updateAppState({isLoading: false, err: reason.message}) } ) } render() { return ( <section className="jumbotron"> <h3 className="jumbotron-heading">搜索Gitee用户</h3> <div> <input ref={c => this.keyWordElement = c} type="text" placeholder="键入想要搜索的内容"/>&nbsp; <button onClick={this.searchUser}>搜索</button> </div> </section> ) } }

components/List/index.jsx

jsx
import React, { Component } from 'react' import './index.css' export default class List extends Component { render() { const {users, isFirst, isLoading, err} = this.props return ( <div className="row"> { isFirst ? <h2>欢迎使用</h2> : isLoading ? <h2>加载中...</h2> : err ? <h2 style={{color: 'red'}}>{err}</h2> : users.map((userObj) => { return ( <div key={userObj.id} className="card"> <a rel="noreferrer" href={userObj.html_url} target="_blank"> <img alt={userObj.name} src={userObj.avatar_url==='https://gitee.com/assets/no_portrait.png' ? 'https://avatars.githubusercontent.com/u/6412038?v=3' : userObj.avatar_url + '!avatar200'} style={{width: '100px'}}/> </a> <p className="card-text">{userObj.login}</p> </div> ) }) } </div> ) } }

消息订阅与发布

在需要接收数据的组件里订阅消息,当其他组件发布该消息时,就会执行其中的回调

使用PubSubJS库:npm install pubsub-js

引入PubSubJS库:import PubSub from 'pubsub-js'

App组件删除所有与state相关的操作,将state保存在List组件中

List组件中消息订阅;

jsx
componentDidMount() { this.token = PubSub.subscribe('state', (msg, data) => { // msg适用于多个订阅时,区分订阅来源 this.setState(data) }) } componentWillUnmount() { PubSub.unsubscribe(this.token) // 在组件销毁前取消订阅,防止状态泄露 }

Search组件中消息发布:

jsx
searchUser = () => { // 获取用户的输入 const {keyWordElement: {value: keyWord}} = this // 解构赋值的连续写法 + 重命名 // 发送请求前通知List更新状态 PubSub.publish('state', {isFirst: false, isLoading: true}) // 发送网络请求 axios.get(`https://gitee.com/api/v5/search/users?q=${keyWord}`).then( value => { // 请求成功后通知List更新状态 PubSub.publish('state', {isLoading: false, users: value.data}) }, reason => { // 请求失败后通知List更新状态 PubSub.publish('state', {isLoading: false, err: reason.message}) } ) }

fetch发送请求

fetch文档地址

segmentfault上的fetch介绍

通过console.log()感受一下fetch的“关注分离”:

js
fetch(`https://gitee.com/api/v5/search/users?q=${keyWord}`).then( response => { console.log('联系服务器成功') return response.json() }, reason => {console.log('联系服务器失败', reason)} ).then( response => { console.log('获取数据成功', response); }, reason => {console.log('获取数据失败', reason)} )

image.png

如果联系服务器失败了(比如断网时发送请求)会输出什么?

联系服务器失败 reason 获取数据成功 undefined
  1. fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求
  2. 老版本浏览器可能不支持

全部代码:

jsx
import React, { Component } from 'react' import PubSub from 'pubsub-js' // import axios from 'axios' export default class Search extends Component { searchUser = async() => { // 获取用户的输入 const {keyWordElement: {value: keyWord}} = this // 解构赋值的连续写法 + 重命名 // 发送请求前通知List更新状态 // this.props.updateAppState({isFirst: false, isLoading: true}) PubSub.publish('state', {isFirst: false, isLoading: true}) //#region 发送网络请求 --- 使用axios发送 /* axios.get(`https://gitee.com/api/v5/search/users?q=${keyWord}`).then( value => { // 请求成功后通知List更新状态 // this.props.updateAppState({isLoading: false, users: value.data}) PubSub.publish('state', { isLoading: false, users: value.data }) }, reason => { // 请求失败后通知List更新状态 // this.props.updateAppState({isLoading: false, err: reason.message}) PubSub.publish('state', { isLoading: false, err: reason.message }) } ) */ //#endregion //#region 发送网络请求 --- 使用fetch发送 -- 未优化 /* fetch(`https://gitee.com/api/v5/search/users?q=${keyWord}`).then( response => { console.log('联系服务器成功') return response.json() }, reason => { console.log('联系服务器失败', reason) return new Promise() // 中断Promise链 } ).then( response => { console.log('获取数据成功', response); }, reason => {console.log('获取数据失败', reason)} ) */ //#endregion //#region 发送网络请求 --- 使用fetch发送 -- 优化版本 /* fetch(`https://gitee.com/api/v5/search/users?q=${keyWord}`).then( response => { console.log('联系服务器成功') return response.json() } ).then( response => { console.log('获取数据成功', response); } ).catch( error => {console.log('请求出错', error)} ) */ //#endregion try { const response = await fetch(`https://gitee.com/api/v5/search/users?q=${keyWord}`) const data = await response.json() // await要在async里用 // console.log(data) PubSub.publish('state', { isLoading: false, users: data }) } catch (error) { // console.log('请求出错', error) PubSub.publish('state', { isLoading: false, err: error.message }) } } render() { return ( <section className="jumbotron"> <h3 className="jumbotron-heading">搜索Gitee用户</h3> <div> <input ref={c => this.keyWordElement = c} type="text" placeholder="键入想要搜索的内容"/>&nbsp; <button onClick={this.searchUser}>搜索</button> </div> </section> ) } }

总结

  1. 设计状态时要考虑全面,例如带有网络请求的组件,要考虑请求失败怎么办

  2. ES6解构赋值+重命名:

    js
    let obj = {a: {b: 1}} const {a} = obj // 传统解构赋值 const {a: {b}} = obj // 连续解构赋值 const {a: {b: value}} = obj // 连续解构赋值 + 重命名
  3. 消息订阅与发布机制

    • 先订阅,再发布
    • 适用于任意组件间通信
    • 要在组件的componentWillUnmount中取消订阅
  4. fetch发送请求(关注分离的设计思想)

    js
    try { const response = await fetch(`https://gitee.com/api/v5/search/users?q=${keyWord}`) const data = await response.json() // await要在async里用 // console.log(data) PubSub.publish('state', { isLoading: false, users: data }) } catch (error) { // console.log('请求出错', error) PubSub.publish('state', { isLoading: false, err: error.message }) } // 外面需要包一个 async function

本文作者:Morales

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 License 许可协议。转载请注明出处!