浏览器扩展程序 (FeHelper):有个功能可以自动整理 JSON 格式数据
# React 脚手架配置代理
# 第一种
在 package.json 中添加:
"proxy":"http://localhost:5000(你要代理到的目标地址)"
说明:
- 优点:配置简单,前端请求资源时可以不加任何前缀。
- 缺点:不能配置多个代理。
- 工作方式:上述方式配置代理,当请求了 3000 不存在的资源时,那么该请求会转发给 5000 (优先匹配前端资源)
- 案例
import React, { Component } from "react";
import axios from "axios";
export default class App extends Component {
getStudentData = () => {
// 此处是localhost:3000(就是代理服务器)
// 代理服务器默认端口是:客户端的端口号(3000)
axios.get("http://localhost:3000/api1/students").then(
(response) => {
console.log("成功了", response.data);
},
(error) => {
console.log("失败了", error);
}
);
};
getCarData = () => {
axios.get("http://localhost:3000/api2/cars").then(
(response) => {
console.log("成功了", response.data);
},
(error) => {
console.log("失败了", error);
}
);
};
render() {
return (
<div>
<button onClick={this.getStudentData}>点我获取学生数据</button>
<button onClick={this.getCarData}>点我获取汽车数据</button>
</div>
);
}
}
# 第二种:要配置多种代理时
-
第一步:创建代理配置文件
在src下创建配置文件:src/setupProxy.js -
编写 setupProxy.js 配置具体代理规则:
const proxy = require("http-proxy-middleware"); module.exports = function (app) { app.use( proxy("/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": "" }, //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置) }), proxy("/api2", { target: "http://localhost:5001", changeOrigin: true, pathRewrite: { "^/api2": "" }, }) ); };
说明:
- 优点:可以配置多个代理,可以灵活的控制请求是否走代理。
- 缺点:配置繁琐,前端请求资源时必须加前缀 (比如 /api1)。
# GitHub 搜索案例
# Axios
-
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: "", //存储请求相关的错误信息 }; //更新App的state updateAppState = (stateObj) => { this.setState(stateObj); }; render() { return ( <div className="container"> <Search updateAppState={this.updateAppState} /> <List {...this.state} /> </div> ); } } -
Search.jsx
import React, { Component } from "react"; export default class Search extends Component { search = () => { //获取用户的输入(连续解构赋值+重命名) //此处的value是解构赋值,keyword是重命名 const { keyWordElement: { value: keyWord }, } = this; //发送请求前通知App更新状态 this.props.updateAppState({ isFirst: false, isLoading: true }); //发送网络请求 axios.get(`/api1/search/users?q=${keyWord}`).then( (response) => { //请求成功后通知App更新状态 this.props.updateAppState({ isLoading: false, users: response.data.items, }); }, (error) => { //请求失败后通知App更新状态 this.props.updateAppState({ isLoading: false, err: error.message }); } ); }; render() { return ( <section className="jumbotron"> <h3 className="jumbotron-heading">搜索github用户</h3> <div> <input ref={(c) => (this.keyWordElement = c)} type="text" placeholder="输入关键词点击搜索" /> <button onClick={this.search}>搜索</button> </div> </section> ); } } -
List.jsx
import React, { Component } from "react"; export default class List extends Component { render() { const { users, isFirst, isLoading, 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} className="card"> <a rel="noreferrer" href={userObj.html_url} target="_blank"> <img alt="head_portrait" src={userObj.avatar_url} style={{ width: "100px" }} /> </a> <p className="card-text">{userObj.login}</p> </div> ); }) )} </div> ); } } -
setupProxy.js
const proxy = require("http-proxy-middleware"); module.exports = function (app) { app.use( proxy("/api1", { //遇见/api1前缀的请求,就会触发该代理配置 target: "http://localhost:5000", //请求转发给谁 changeOrigin: true, //控制服务器收到的请求头中Host的值 pathRewrite: { "^/api1": "" }, //重写请求路径(必须) }) ); };
# 兄弟组件之间如何进行交互 (任意组件之间也可以这样使用)–消息订阅 - 发布机制
-
工具库: PubSubJS
-
下载: npm install pubsub-js --save
-
使用:
- import PubSub from ‘pubsub-js’ // 引入
- PubSub.subscribe (‘delete’, function (data){ }); // 订阅
- PubSub.publish (‘delete’, data) // 发布消息
-
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 ( <div className="container"> <Search /> <List /> </div> ); } } -
Search.jsx
import React, { Component } from "react"; import PubSub from "pubsub-js"; export default class Search extends Component { search = () => { const { keyWordElement: { value: keyWord }, } = this; // 发送消息前通知List更新状态 // publish 是发布消息 PubSub.publish("hh", { isFirst: false, isLoading: true }); axios.get(`/api1/search/users?q=${keyWord}`).then( (response) => { PubSub.publish("hh", { isLoading: false, users: response.data.items, }); }, (error) => { PubSub.publish("hh", { isLoading: false, err: error.message }); } ); }; render() { return ( <section className="jumbotron"> <h3 className="jumbotron-heading">搜索github用户</h3> <div> <input ref={(c) => (this.keyWordElement = c)} type="text" placeholder="输入关键词点击搜索" /> <button onClick={this.search}>搜索</button> </div> </section> ); } } -
List.jsx
import React, { Component } from "react"; import PubSub from "pubsub-js"; export default class List extends Component { state = { //初始化状态 users: [], //users初始值为数组 isFirst: true, //是否为第一次打开页面 isLoading: false, //标识是否处于加载中 err: "", //存储请求相关的错误信息 }; componentDidMount() { // subscribe 是订阅消息 // 如果有人发布了hh这个消息,就会执行第二个函数 // 第二个函数有两个参数:第一个是消息名,第二个是数据(发布者发布的数据) this.token = PubSub.subscribe("hh", (msg, stateObj) => { this.setState(stateObj); }); } componentWillUnmount() { // unsubscribe 是取消订阅 PubSub.unsubscribe(this.token); } render() { const { users, isFirst, isLoading, 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} className="card"> <a rel="noreferrer" href={userObj.html_url} target="_blank"> <img alt="head_portrait" src={userObj.avatar_url} style={{ width: "100px" }} /> </a> <p className="card-text">{userObj.login}</p> </div> ); }) )} </div> ); } }
# Fetch
# 文档
# 特点
- fetch: 原生函数,不再使用 XmlHttpRequest 对象提交 ajax 请求
- 老版本浏览器可能不支持
# 相关 API
-
GET
fetch(url) .then(function (response) { return response.json(); }) .then(function (data) { console.log(data); }) .catch(function (e) { console.log(e); }); -
POST
fetch(url, { method: "POST", body: JSON.stringify(data), }) .then(function (data) { console.log(data); }) .catch(function (e) { console.log(e); });
# 案例
import React, { Component } from "react";
import PubSub from "pubsub-js";
export default class Search extends Component {
search = async () => {
//发送网络请求---使用fetch发送(未优化)
/* fetch(`/api1/search/users2?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(`/api1/search/users2?q=${keyWord}`);
const data = await response.json();
console.log("请求成功", data.items);
} catch (error) {
console.log("请求出错", error.message);
}
};
render() {
return <button onClick={this.search}>搜索</button>;
}
}
# GitHub 搜索案例总结
-
设计状态时要考虑全面,例如带有网络请求的组件,要考虑请求失败怎么办。
-
ES6 小知识点:解构赋值 + 重命名
let obj = { a: { b: 1 } }; const { a } = obj; //传统解构赋值 const { a: { b }, } = obj; //连续解构赋值 const { a: { b: value }, } = obj; //连续解构赋值+重命名 -
消息订阅与发布机制
- 先订阅,再发布(理解:有一种隔空对话的感觉)
- 适用于任意组件间通信
- 要在组件的 componentWillUnmount 中取消订阅
-
fetch 发送请求(关注分离的设计思想)
try { const response = await fetch(`/api1/search/users2?q=${keyWord}`); const data = await response.json(); console.log(data); } catch (error) { console.log("请求出错", error); }
# React 路由
# SPA 的理解
- 单页 Web 应用(single page web application,SPA)。
- 整个应用只有一个完整的页面 (public 下的 index.html)。
- 点击页面中的链接不会刷新页面,只会做页面的局部更新。
- 数据都需要通过 ajax 请求获取,并在前端异步展现。
# 路由的理解
# 什么是路由
- 一个路由就是一个映射关系 (key:value)
- key 为路径,value 可能是 function 或 component
- 路由主要是对浏览器的历史记录进行操作
# 路由分类
-
后端路由
- 理解: value 是 function, 用来处理客户端提交的请求。
- 注册路由:
router.get(path, function(req, res)) - 工作过程:当 node 接收到一个请求时,根据请求路径找到匹配的路由,调用路由中的函数来处理请求,返回响应数据
-
前端路由
- 浏览器端路由,value 是 component,用于展示页面内容。
- 注册路由:
<Route path="/test" component={Test}> - 工作过程:当浏览器的 path 变为 /test 时,当前路由组件就会变为 Test 组件
# react-route-dom
下载:npm install --save react-router-dom
# 理解
- react 的一个插件库。
- 专门用来实现一个 SPA 应用。
- 基于 react 的项目基本都会用到此库。
# 相关 API
-
内置组件
<BrowserRouter><HashRouter><Route><Redirect><Link><NavLink><Switch>
# 路由的基本使用
-
index.js
import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter } from "react-router-dom"; import App from "./App"; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById("root") ); -
App.jsx
import React, { Component } from "react"; import { Link, Route } from "react-router-dom"; import Home from "./components/Home"; import About from "./components/About"; export default class App extends Component { render() { return ( <div> <div className="list-group"> {/* 在React中靠路由链接实现切换组件--编写路由链接 */} {/* Link 只是普通跳转 */} {/* NavLink可以实现路由链接的高亮,通过activeClassName指定样式名 */} {/* 通过this.props.children可以获取标签体内容 */} <NavLink activeClassName="xiaoguo" className="list-group-item" to="/about" > About </NavLink> <NavLink activeClassName="xiaoguo" className="list-group-item" to="/home" > Home </NavLink> </div> <div className="panel-body"> {/* 注册路由 */} {/* 通过Route标签进行路径的匹配 */} <Route path="/about" component={About} /> <Route path="/home" component={Home} /> </div> </div> ); } } -
About.jsx
import React, { Component } from "react"; export default class About extends Component { render() { return <h3>我是About的内容</h3>; } } -
Home.jsx
import React, { Component } from "react"; export default class Home extends Component { render() { return <h3>我是Home的内容</h3>; } }
# 路由组件和一般组件
-
写法不同:
一般组件:<Demo/>
路由组件:<Route path="/demo" component={Demo}/> -
存放位置不同:
一般组件:components
路由组件:pages -
接收到的 props 不同:
一般组件:写组件标签时传递了什么,就能收到什么
路由组件:接收到三个固定的属性history: go: ƒ go(n) goBack: ƒ goBack() goForward: ƒ goForward() push: ƒ push(path, state) replace: ƒ replace(path, state) location: pathname: "/about" search: "" state: undefined match: params: {} path: "/about" url: "/about"
# Switch 的使用
- 通常情况下,path 和 component 是一一对应的关系。
- Switch 可以提高路由匹配效率 (单一匹配)。
<NavLink
activeClassName="xiaoguo"
className="list-group-item"
to="/home"
>
Home
</NavLink>
<Switch>
<Route path="/about" component={About} />
<Route path="/home" component={Home} />
// 加了Switch之后:匹配到第一个path相同的组件就不往下匹配了
<Route path="/home" component={Test} />
</Switch>;
# 解决多级路径刷新页面样式丢失的问题
- public/index.html 中 引入样式时不写 ./ 写 / (常用):例如./css/route.css 写成 /css/route.css
- public/index.html 中 引入样式时不写 ./ 写 % PUBLIC_URL% (常用)例如:./css/route.css 写成 % PUBLIC_URL%/css/route.css, % PUBLIC_URL% 代表 public 的绝对路径,只适用于 react 脚手架里这样写。
- 在 index.js 中使用 HashRouter,因为 #/ 之后的内容,都认识是前端资源,根本不带给前边的服务器 (localhost:3000/)
# 路由的严格匹配与模糊匹配
- 默认使用的是模糊匹配(简单记:【输入的路径】必须包含要【匹配的路径】,且顺序要一致)
- 开启严格匹配:
<Route exact path="/about" component={About}/> - 严格匹配不要随便开启,需要再开,有些时候开启会导致无法继续匹配二级路由
# Redirect 的使用
-
一般写在所有路由注册的最下方,当所有路由都无法匹配时,跳转到 Redirect 指定的路由
-
具体编码:
<Switch> <Route path="/about" component={About} /> <Route path="/home" component={Home} /> // 当上面两个都没匹配上,就走重定向 <Redirect to="/about" /> </Switch>
# 嵌套路由
- 注意:注册子路由时要写上父路由的 path 值
- 路由的匹配是按照注册路由的顺序进行的
# 向路由组件传递参数
-
params 参数
路由链接 (携带参数):<Link to='/demo/test/tom/18'}>详情</Link>
注册路由 (声明接收):<Route path="/demo/test/:name/:age" component={Test}/>
在 Test 组件中接收参数:const {name,age} = this.props.match.params -
search (query) 参数
路由链接 (携带参数):<Link to='/demo/test?name=tom&age=18'}>详情</Link>
注册路由 (无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
接收参数:this.props.location.search
备注:获取到的 search 是 urlencoded 编码字符串,需要借助 querystring 解析 (通过 parse (),stringify () 方法去解析) -
state 参数
路由链接 (携带参数):<Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>
注册路由 (无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
接收参数:this.props.location.state || {}
备注:刷新也可以保留住参数,因为 BrowserRouter 会默认操作 history 对象,history 会帮你完成这一操作,但如果你把浏览器缓存清掉之后就会报错,这也是为什么要用 {} 的原因
# 路由跳转的两种模式
默认是 push 模式 (压栈),加上 replace 之后就是替换模式
<Link replace to='/demo/test/tom/18'}>详情</Link>
# 编程式路由导航
借助 this.prosp.history 对象上的 API 对操作路由跳转、前进、后退
-
this.prosp.history.push()
-
this.prosp.history.replace()
-
this.prosp.history.goBack()
-
this.prosp.history.goForward()
-
this.prosp.history.go()
-
举例:
replaceShow = (id, title) => { //replace跳转+携带params参数 //this.props.history.replace(`/home/message/detail/${id}/${title}`) //replace跳转+携带search参数 // this.props.history.replace(`/home/message/detail?id=${id}&title=${title}`) //replace跳转+携带state参数 this.props.history.replace(`/home/message/detail`, { id, title }); }; pushShow = (id, title) => { //push跳转+携带params参数 // this.props.history.push(`/home/message/detail/${id}/${title}`) //push跳转+携带search参数 // this.props.history.push(`/home/message/detail?id=${id}&title=${title}`) //push跳转+携带state参数 this.props.history.push(`/home/message/detail`, { id, title }); }; back = () => { this.props.history.goBack(); }; forward = () => { this.props.history.goForward(); }; go = () => { this.props.history.go(-2); }; /* 向路由组件传递params参数 */ /* <Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link> */ /* 向路由组件传递search参数 */ /* <Link to={`/home/message/detail/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link> */ /* 向路由组件传递state参数 */ <Link to={{ pathname: "/home/message/detail", state: { id: msgObj.id, title: msgObj.title }, }} > {msgObj.title} </Link> <button onClick={() => this.pushShow(msgObj.id, msgObj.title)}> push查看 </button> <button onClick={() => this.replaceShow(msgObj.id, msgObj.title)}> replace查看 </button>;
# withRouter 的使用
withRouter 用来解决在一般组件中使用路由组件 API 的问题
import React, { Component } from "react";
import { withRouter } from "react-router-dom";
class Header extends Component {}
// withRouter能接收一个一般组件,然后就把这个一般组件的身上加上了路由组件所特有的属性:history,location,match
// 也就是说withRouter让一般组件具备路由组件所特有的API
// withRouter的返回值是一个新组件
export default withRouter(Header);
# BrowserRouter 与 HashRouter 的区别
- 底层原理不一样:
BrowserRouter 使用的是 H5 的 history API,不兼容 IE9 及以下版本。
HashRouter 使用的是 URL 的哈希值。 - path 表现形式不一样
BrowserRouter 的路径中没有 #, 例如:localhost:3000/demo/test
HashRouter 的路径包含 #, 例如:localhost:3000/#/demo/test - 刷新后对路由 state 参数的影响
(1).BrowserRouter 没有任何影响,因为 state 保存在history对象中。
(2).HashRouter 刷新后会导致路由state 参数的丢失!!! - 备注:HashRouter 可以用于解决一些路径错误相关的问题。