尚硅谷 2021 版 React 技术全家桶全套完整版(零基础入门到精通/男神天禹老师亲授)
方法一:配置一个代理
在 package.json 中配置 "proxy": "http://localhost:5000"
现在你在 3000 端口给 3000 代理服务器发送数据,代理服务器帮你向 5000 发送数据
注意:3000 端口是服务器帮你开启的根路径(public),如果 public 有这个文件,就不会帮你向代理服务器转发
import axios from 'axios'
import React, { Component } from 'react'
export default class App extends Component {
getStudentData = () => {
axios
.get('http://localhost:3000/api1/students')
.then(res => console.log('student', res.data))
.catch(err => console.log(err))
}
render() {
return (
)
}
}
方法二:配置多个代理
在 src 目录下新建 setupProxy.js
注意:这个文件需要使用 CommonJS 语法,因为脚手架会帮你找到这个文件,并将其添加到 Webpack 配置项中
具体配置如下:
changeOrigin 设置为 true 时,服务器收到的请求头中的 Host 为:locahost:5000
changeOrigin 设置为 false 时,服务器收到的请求头中的 Host 为:localhost:3000
changeOrigin 默认值为 false,但一般将其设置为 true
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
proxy('/api1', {
//api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)
target: 'http://localhost:5000', //配置转发目标地址(能返回数据的服务器地址)
changeOrigin: true, // 控制服务器收到请求头Host字段的值
pathRewrite: {
'^/api1': '' }, //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置))
}),
proxy('/api2', {
target: 'http://localhost:5001',
changeOrigin: true,
pathRewrite: {
'^/api2': '' },
})
)
}
class=
批量替换成 className=
let obj = {
a: {
b: 1 } }
const {
a } = obj // 传统解构赋值
const {
a: {
b },
} = obj // 连续解构赋值
const {
a: {
b: value },
} = obj // 连续解构赋值+重命名
App.jsx
import React, { Component } from 'react'
import Search from './components/Search'
import List from './components/List'
export default class App extends Component {
state = {
users: [], // users初始值为数组
isFirst: true, // 是否为第一次打开页面
isLoading: false, // 标识是否处于加载中,
err: '', //存储请求相关的错误信息
}
updateAppState = stateObj => {
this.setState(stateObj)
}
render() {
return (
)
}
}
List.jsx
import axios from 'axios'
import React, { Component } from 'react'
export default class Search extends Component {
search = () => {
const {
keyWordElement: { value: keyWord },
} = this
this.props.updateAppState({ isFirst: false, isLoading: true })
axios
.get(`http://localhost:3000/api1/search/users2?q=${keyWord}`)
.then(res => {
this.props.updateAppState({ isLoading: false, users: res.data.items })
})
.catch(err => {
this.props.updateAppState({ isLoading: false, err: err.message })
})
}
render() {
return (
Search Github Users
(this.keyWordElement = c)} type="text" placeholder="enter the name you search" />
)
}
}
Search.jsx
import React, { Component } from 'react'
import './index.css'
export default class List extends Component {
render() {
const { users, isFirst, isLoading, err } = this.props
return (
)
}
}
yarn add pubsub-js
App.jsx
import React, { Component } from 'react'
import Search from './components/Search'
import List from './components/List'
export default class App extends Component {
render() {
return (
)
}
}
List.jsx
import React, { Component } from 'react'
import './index.css'
import PubSub from 'pubsub-js'
export default class List extends Component {
state = {
users: [],
isFirst: true,
isLoading: false,
err: '',
}
componentDidMount() {
this.token = PubSub.subscribe('keyWord', (_, stateObj) => {
this.setState(stateObj)
})
}
componentWillUnmount() {
PubSub.unsubscribe(this.token)
}
render() {
const { users, isFirst, isLoading, err } = this.state
return (
)
}
}
Search.jsx
import axios from 'axios'
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class Search extends Component {
search = () => {
const {
keyWordElement: { value: keyWord },
} = this
PubSub.publish('keyWord', { isFirst: false, isLoading: true })
axios
.get(`http://localhost:3000/api1/search/users2?q=${keyWord}`)
.then(res => {
PubSub.publish('keyWord', { isLoading: false, users: res.data.items })
})
.catch(err => {
PubSub.publish('keyWord', { isLoading: false, err: err.message })
})
}
render() {
return (
Search Github Users
(this.keyWordElement = c)} type="text" placeholder="enter the name you search" />
)
}
}
//#region
、 //#endregion
可以让代码注释
传统 Ajax 已死,Fetch 永生
search = async () => {
const {
keyWordElement: { value: keyWord },
} = this
PubSub.publish('keyWord', { isFirst: false, isLoading: true })
//#region 正常版 fetch 发送请求
/* fetch(`/api1/search/users2?q=${keyWord}`)
.then(res => {
console.log('联系服务器成功了', res)
return res.json()
})
.then()
.catch(err => console.log('联系服务器失败了', err)) */
//#endregion
‘
// 优化版 fetch 发送请求
try {
const response = await fetch(`/api1/search/users2?q=${keyWord}`)
const data = await response.json()
} catch (error) {
console.log(error)
}
}