文章目录
1 setState
setState
更新状态其实有两种写法,setState这个方法在调用的时候是同步的,但是引起React的状态更新是异步的
写法一:对象式
setState(stateChange, [callback])
stateChange
为状态改变对象 (该对象可以体现出状态的更改)callback
是可选的回调函数, 它在状态更新完毕、界面也更新后(render
调用后)才被调用,异步更新后调用,可以拿到更新后的状态的值
this.setState({ count: this.state.count+1 })
写法二:函数式
setState(updater, [callback])
updater
为返回stateChange
对象的函数,返回值是对象updater
可以接收到state
和props
callback
是可选的回调函数, 它在状态更新、界面也更新后(render
调用后)才被调用,和对象式是一样的
传的时候回调函数,可以接收到state和props,函数的返回值是设置状态的对象
setState(state => ({count: state.count+1}))
总结:
- 对象式的
setState
是函数式的setState
的简写方式(语法糖) - 使用原则:
- 如果新状态不依赖于原状态,使用对象方式
- 如果新状态依赖于原状态 ,使用函数方式
- 如果需要在
setState()
执行后,获取最新的状态数据,可以在第二个callback
函数中读取到异步更新的最新值
2 路由组件懒加载
懒加载
:用的时候才加载,一般是路由组件进行懒加载,如果不用路由懒加载,页面在第一次进入的时候,就请求了所有组件的数据,如果组件过多,过多的请求这就没有必要了,应该是用户按哪个链接再请求哪个组件
如何使用?
-
通过React的
lazy
函数配合import()
函数动态加载路由组件,路由组件代码会被分开打包 -
通过
<Suspense>
指定在加载得到路由打包文件前显示一个自定义loading界面
import React, { Component, lazy, Suspense} from 'react'
import {NavLink,Route} from 'react-router-dom'
// import Home from './Home'
// import About from './About'
import Loading from './Loading'
const Home = lazy(()=> import('./Home') )
const About = lazy(()=> import('./About'))
export default class Demo extends Component {
render() {
return (
<div>
<div className="row">
<div className="col-xs-offset-2 col-xs-8">
<div className="page-header"><h2>React Router Demo</h2></div>
</div>
</div>
<div className="row">
<div className="col-xs-2 col-xs-offset-2">
<div className="list-group">
{/* 在React中靠路由链接实现切换组件--编写路由链接 */}
<NavLink className="list-group-item" to="/about">About</NavLink>
<NavLink className="list-group-item" to="/home">Home</NavLink>
</div>
</div>
<div className="col-xs-6">
<div className="panel">
<div className="panel-body">
<Suspense fallback={<Loading/>}>
{/* 注册路由 */}
<Route path="/about" component={About}/>
<Route path="/home" component={Home}/>
</Suspense>
</div>
</div>
</div>
</div>
</div>
)
}
}
3 Fragments
在React中,组件是不允许返回多个节点的,如:
return
<p>React</p>
<p>Vue</p>
我们想要解决这种情况需要给为此套一个容器元素,如
return
<div>
<p>React</p>
<p>Vue</p>
</div>
但这样做,无疑会多增加一个节点,所以在16.0后,官方推出了Fragment碎片概念,能够让一个组件返回多个元素,React.Fragment 等价于<></>
Fragments
允许你将子列表分组,而无需向 DOM 添加额外节点。 可以不用必须有一个真实的DOM根标签了
<Fragment><Fragment>
// 或者
<></>
//在循环数组时,我们必须要有key,实际上<React.Fragment>允许有key的,而<></>无法附上key,所以这是两者的差距
4 Context
Context
提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。常用于祖组件与后代组件间通信
在实际开发项目的时候我们可能会经常碰到多层组件传值的情况,就是父组件的值传递给子组件。子组件再传递给下面的子组件,再传递给下面的子组件…可能会遇到这个情况。
使用方式,需要在父组件上面创建一个context,或者建立一个文件用来管理context。
如何使用?
-
在父组件上面创建一个context,或者建立一个文件用来管理context。
//createContext.jsx 文件 const XxxContext = React.createContext()
-
父组件通过Provider包裹子组件,通过value={ }携带参数,value可以为对象或函数。这个Provider可以理解为生产者。 通过value属性给后代组件传递数据:
<xxxContext.Provider value={数据}> 子组件 </xxxContext.Provider>
-
后代组件读取数据:
-useContext用来获取父级组件传递过来的 context 值,这个当前值就是最近的父级组件 Provider 设置的 value 值,useContext 参数一般是由 createContext 方式创建的,也可以父级上下文 context 传递的 ( 参数为 context )。useContext 可以代替 context.Consumer 来获取 Provider 中保存的 value 值
<xxxContext.Consumer>
{
value => ( // value就是context中的value数据
要显示的内容
)
}
</xxxContext.Consumer>
// 或
function Item() {
//接收contex对象,并返回该context的值
//该值由上层组件中距离当前组件最近的<xxxContext.Provider>的value prop决定
const num = useContext(xxxContext)//useContext的参数必须是context对象本身:
//调用了useContext的组件总会在context值变化时重新渲染,上层数据发生改变,肯定会触发重新渲染
return <div>子组件 {num}</div>
5 组件优化
Component存在的问题:
- 只要执行setState( ),即使不改变状态数据, 组件也会重新render( ) ==> 效率低
- 只当前组件重新render( ), 就会自动重新render子组件,纵使子组件没有用到父组件的任何数据 ==> 效率低
原因
:Component中的shouldComponentUpdate( )总是返回true
如何解决
:只有当组件的state或props数据发生改变时才重新render( )
解决方法:
办法一: 重写shouldComponentUpdate()
方法
比较新旧state或props数据, 如果有变化才返回true, 如果没有返回false
shouldComponentUpdate(nextProps,nextState){
// console.log(this.props,this.state); //目前的props和state
// console.log(nextProps,nextState); //接下要变化的目标props,目标state
return !this.state.carName === nextState.carName
}
办法二: 使用PureComponent
PureComponent重写了shouldComponentUpdate(), 只有state或props数据有变化才返回true
注意:
- 只是进行state和props数据的浅比较, 如果只是数据对象内部数据变了, 返回false
- 不要直接修改state数据, 而是要产生新数据
项目中一般使用PureComponent
来优化
import React, { PureComponent } from 'react'
import './index.css'
export default class Parent extends PureComponent {
state = {carName:"奔驰c36",stus:['小张','小李','小王']}
addStu = ()=>{
/* const {stus} = this.state
stus.unshift('小刘')
this.setState({stus}) */
const {stus} = this.state
this.setState({stus:['小刘',...stus]})
}
changeCar = ()=>{
this.setState({carName:'迈巴赫'})
// const obj = this.state
// obj.carName = '迈巴赫'
// console.log(obj === this.state);
// this.setState(obj)
}
/* shouldComponentUpdate(nextProps,nextState){
// console.log(this.props,this.state); //目前的props和state
// console.log(nextProps,nextState); //接下要变化的目标props,目标state
return !this.state.carName === nextState.carName
} */
render() {
console.log('Parent---render');
const {carName} = this.state
return (
<div className="parent">
<h3>我是Parent组件</h3>
{this.state.stus}
<span>我的车名字是:{carName}</span><br/>
<button onClick={this.changeCar}>点我换车</button>
<button onClick={this.addStu}>添加一个小刘</button>
<Child carName="奥拓"/>
</div>
)
}
}
class Child extends PureComponent {
/* shouldComponentUpdate(nextProps,nextState){
console.log(this.props,this.state); //目前的props和state
console.log(nextProps,nextState); //接下要变化的目标props,目标state
return !this.props.carName === nextProps.carName
} */
render() {
console.log('Child---render');
return (
<div className="child">
<h3>我是Child组件</h3>
<span>我接到的车是:{this.props.carName}</span>
</div>
)
}
}
6 render props
标签体
:<h1>我是标签体</h1>
在起始标签和闭合标签之间的内容即为标签体
如何向组件内部动态传入带内容的标签?(如何把第三个组件摆在某一个指定位置并传递数据)
- 使用
children props
: 通过组件标签体传入结构 - 使用
render props
: 通过组件标签属性传入结构,而且可以携带数据,一般用render
函数属性
方法一:children props
<A>
<B/>
</A>
// 使用
{this.props.children}
import React, { Component } from 'react';
import './index.css';
export default class Parent extends Component {
render() {
return (
<div className="parent">
<h3>我是Parent组件</h3>
<A>
<B />
</A>
</div>
);
}
}
class A extends Component {
state = { name: 'tom' };
render() {
console.log(this.props);
const { name } = this.state;
return (
<div className="a">
<h3>我是A组件</h3>
{/* this.props.children展示标签体<B/> */}
{this.props.children}
</div>
);
}
}
class B extends Component {
render() {
console.log('B--render');
return (
<div className="b">
<h3>我是B组件,</h3>
</div>
);
}
}
方法二:render props
<A render={(data) => <B data={data}/>}></A>
//使用
A组件: `{this.props.render(内部state数据)}`
B组件: 读取A组件传入的数据显示 `{this.props.data}`
import React, { Component } from 'react';
import './index.css';
export default class Parent extends Component {
render() {
return (
<div className="parent">
<h3>我是Parent组件</h3>
//需求:在组件A中显示组件B,并将name值传递给B
<A render={name => <B name={name} />} />
</div>
);
}
}
class A extends Component {
state = { name: 'tom' };
render() {
const { name } = this.state;
return (
<div className="a">
<h3>我是A组件</h3>
{this.props.render(name)}
</div>
);
}
}
class B extends Component {
render() {
return (
<div className="b">
<h3>我是B组件,{this.props.name}</h3>
</div>
);
}
}
7 错误边界
错误边界(Error boundary)
:用来捕获后代组件错误,渲染出备用页面
特点:
只能捕获后代组件生命周期产生的错误,不能捕获自己组件产生的错误和其他组件在合成事件、定时器中产生的错误
使用方式
:getDerivedStateFromError配合componentDidCatch
// 生命周期函数,一旦后台组件报错,就会触发
static getDerivedStateFromError(error) {
console.log(error);
// 在render之前触发
// 返回新的state
return {
hasError: true,
};
}
componentDidCatch(error, info) {
// 统计页面的错误。发送请求发送到后台去
console.log(error, info);
}
示例代码
import React, { Component } from 'react'
import Child from './Child'
export default class Parent extends Component {
state = {
hasError:'' // 用于标识子组件是否产生错误
}
//当Parent的子组件出现报错时候,会触发getDerivedStateFromError调用,并携带错误信息
static getDerivedStateFromError(error){
console.log('@@@',error);
return {hasError:error}
}
componentDidCatch(){
console.log('此处统计错误,反馈给服务器,用于通知编码人员进行bug的解决');
}
render() {
return (
<div>
<h2>我是Parent组件</h2>
{this.state.hasError ? <h2>当前网络不稳定,稍后再试</h2> : <Child/>}
</div>
)
}
}
8 消息订阅-发布机制
安装 PubSubJS
npm install pubsub-js
使用: 在接收数据的组件中订阅消息
import PubSub from 'pubsub-js'
// 发布(发送数据)
PubSub.publish('名称', argument)
// 订阅(接受数据)
PubSub.subscrib('名称', (msg,argument) => {}
PubSub.unsubscrib('名称')
9 组件通信方式总结
父子组件
:props(children props、render props)兄弟组件(非嵌套组件)
:消息订阅-发布、集中式管理祖孙组件(跨级组件)
:消息订阅-发布、集中式管理、Context
10 React.forwardRef转发以及useImperativeHandle向父组件暴露一个自定义的 ref
forwardRef:使用 forwardRef() 让组件接收 ref 并将其传递给子组件
useImperativeHandle 控制自定义组件中向外暴露哪些组件属性或方法
React.forwardRef 会创建一个React组件,这个组件能够将其接受的 ref 属性转发到其组件树下的另一个组件中。这种技术并不常见,但在以下两种场景中特别有用:
- 转发 ref 到 DOM 组件
- 在高阶组件中转发 ref
该 Form 组件 将 ref 传递至 MyInput。MyInput 组件将该 ref 转发 至 浏览器标签。因此,Form 组件可以访问该 DOM 节点并对其调用 focus()。
import { forwardRef } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
const { label, ...otherProps } = props;
return (
<label>
{label}
<input {...otherProps} ref={ref} />
</label>
);
});
function Form() {
const ref = useRef(null);
function handleClick() {
ref.current.focus();
}
return (
<form>
<MyInput label="Enter your name:" ref={ref} />
<button type="button" onClick={handleClick}>
编辑
</button>
</form>
);
}
import { forwardRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
useImperativeHandle(ref, () => {
return {
// ... 你的方法 ...
};
}, []);
import { useRef } from 'react';
import MyInput from './MyInput.js';
export default function Form() {
const ref = useRef(null);
function handleClick() {
ref.current.focus();
}
return (
<form>
<MyInput placeholder="Enter your name" ref={ref} />
<button type="button" onClick={handleClick}>
Edit
</button>
</form>
);
}
import { forwardRef, useRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => {
return {
focus() {
inputRef.current.focus();
},
scrollIntoView() {
inputRef.current.scrollIntoView();
},
};
}, []);
return <input {...props} ref={inputRef} />;
});
export default MyInput;
在上述的示例中,父组件获得了 MyInput 的 ref,就能通过该 ref 来调用 focus 和 scrollIntoView 方法。然而,它的访问是受限的,无法读取或调用下方 DOM 节点的其他所有属性和方法。
注意:
- 不要滥用 ref。 你应当仅在你没法通过 prop 来表达 命令式 行为的时候才使用 ref:例如,滚动到指定节点、聚焦某个节点、触发一次动画,以及选择文本等等。
- 如果可以通过 prop 实现,那就不应该使用 ref。例