一、 setState
setState更新状态的2种写法
(1). setState(stateChange, [callback])------对象式的setState
1.stateChange为状态改变对象(该对象可以体现出状态的更改)
2.callback是可选的回调函数, 它在状态更新完毕、界面也更新后(render调用后)才被调用
this.setState(
{count:++count},
()=>{console.log("render执行后的回调",this.state.count)}
);
(2). setState(updater, [callback])------函数式的setState
1.updater为 返回 stateChange对象的函数。
2.updater可以接收到 state和props。
3.callback 同上。
this.setState(
(state,props)=>{ return {count:this.state.count+1} },
()=>{console.log("render执行后的回调",this.state.count)}
)
总结:
- 对象式的setState是函数式的setState的简写方式(语法糖)
- 使用原则(仅供参考):
(1).如果新状态不依赖于原状态 => 使用对象方式
(2).如果新状态依赖于原状态 => 使用函数方式
(3).如果需要在setState()执行后获取最新的状态数据,要在第二个callback函数中读取
二、 lazyLoad 懒加载
路由组件的lazyLoad
//1.通过React的lazy函数配合import()函数动态加载路由组件 ===> 路由组件代码会被分开打包
const Login = lazy(()=>import('@/pages/Login'))
//2.通过```<Suspense>```指定在加载得到路由打包文件前显示一个自定义loading界面
<Suspense fallback={<h1>loading.....</h1>}>
<Switch>
<Route path="/xxx" component={Xxxx}/>
<Redirect to="/login"/>
</Switch>
</Suspense>
三、 Hooks (useState、useEffect、useRef) 【重要】
- React Hook/Hooks是什么?
(1). Hook是React 16.8.0版本增加的新特性/新语法
(2). 可以让你在函数组件中使用 state 以及其他的 React 特性 - 三个常用的Hook
(1). State Hook: React.useState()
(2). Effect Hook: React.useEffect()
(3). Ref Hook: React.useRef()
1. State Hook
(1). State Hook让函数组件也可以有state状态, 并进行状态数据的读写操作
(2). 语法: const [xxx, setXxx] = React.useState(initValue)
(3). useState()说明:
参数: 第一次初始化指定的值在内部作缓存
返回值: 包含2个元素的数组, 第1个为内部当前状态值, 第2个为更新状态值的函数
(4). setXxx()2种写法:
setXxx(newValue): 参数为非函数值, 直接指定新的状态值, 内部用其覆盖原来的状态值
setXxx(value => newValue): 参数为函数, 接收原本的状态值, 返回新的状态值, 内部用其覆盖原来的状态值
import React,{ useState,useEffect,useRef } from "react" // rfc快速生成函数组件
export default function Count(){ // 函数式组件: 没有this
const [count,setCount] = useState(0);
const [name,setName] = useState("Tom");
function add(){
setCount(count+1); //第一种写法
// setCount(count=>count+1) // 第二种写法
}
function changeName(){
setName("Jack")
}
return (
<div>
<h3>当前求和为:{count}</h3>
<h3>我的名字:{name}</h3>
<button onClick={add}>点我+1</button>
<button onClick={changeName}>点我改名</button>
</div>
)
}
2. Effect Hook
- Effect Hook 可以让你在函数组件中执行副作用操作(用于模拟类组件中的生命周期钩子)
- React中的副作用操作:
1、发ajax请求数据获取
2、设置订阅 / 启动定时器
3、手动更改真实DOM - 语法和说明:
useEffect(() => {
// 在此可以执行任何带副作用操作
return () => { // 在组件卸载前执行
// 在此做一些收尾工作, 比如清除定时器/取消订阅等
}
}, [stateValue]) // 如果指定的是[], 回调函数只会在第一次render()后执行 注意:第二个参数不写全检测、[]:都不检测,[count]只检测count
- 可以把 useEffect Hook 看做如下三个函数的组合
componentDidMount() 组件渲染完成
componentDidUpdate() 组件更新完成
componentWillUnmount() 组件将要卸载
import React,{ useEffect} from "react"
import { root } from "../../index"; // 入口文件
export default function Count(){
const [count,setCount] = useState(0);
function add(){
setCount(count+1); //第一种写法
// setCount(count=>count+1) // 第二种写法
}
function unmount(){
root.unmount();
}
useEffect(()=>{ // 相当于:componentDidMount\componentDidUpdate\componentWillUnmount
console.log("组件渲染完成、组件更新完成")
let timer = setInterval(()=>{
console.log("定时器在跑")
setCount(count=>count+1); // error! setCount(count+1);在这儿有问题
},1000);
// 组件即将卸载
return ()=>{
console.log("组件卸载")
clearInterval(timer);
}
},[])
return (
<div>
<h3>当前求和为:{count}</h3>
<button onClick={add}>点我+1</button>
<button onClick={unmount}>卸载组件</button>
</div>
)
}
3. Ref Hook
(1). Ref Hook可以在函数组件中存储/查找组件内的标签或任意其它数据
(2). 语法: const refContainer = useRef()
(3). 作用:保存标签对象,功能与React.createRef()一样
import React,{ useRef } from "react"
export default function Count(){
const myRef = useRef(); // ref={myRef}
function showInput(){
console.log("输入值",myRef.current.value)
}
return (
<div>
<input ref={myRef} type="text" />
<button onClick={showInput}>打印输入值</button>
</div>
)
}
四、 Fragment 与 空标签<></>
使用:<Fragment><Fragment>
与 <></>
作用:可以不用必须有一个真实的DOM根标签了。
区别:
Fragment标签只能有一个标签属性【key】;若再写其他标签属性就会报错。
<>不能接受键值或属性。
五、 Context 【一般不用,我们用react-redux】
理解:一种组件间通信方式, 常用于【祖组件】与【后代组件】间通信
使用:
- 创建Context容器对象:
const XxxContext = React.createContext()
- 渲染子组时,外面包裹xxxContext.Provider, 通过value属性给后代组件传递数据:
<xxxContext.Provider value={数据}>
子组件
</xxxContext.Provider>
- 后代组件读取数据:2种方法
//第一种方式:仅适用于类组件
static contextType = xxxContext // 声明接收context
this.context // 读取context中的value数据
//第二种方式: 函数组件与类组件都可以
<xxxContext.Consumer>
{ value => () } // value就是context中的value数据要显示的内容
</xxxContext.Consumer>
注意:在应用开发中一般不用context, 一般都用它的封装react插件
六、 组件优化PureComponent
Component的2个问题
- 只要执行setState(),即使不改变状态数据, 组件也会重新render() ==> 效率低
- 只当前组件重新render, 就会自动重新render子组件,纵使子组件没有用到父组件的任何数据 ==> 效率低
原因:Component中的shouldComponentUpdate()总是返回true
效率高的做法: 让当组件的state或props数据发生改变时才重新render()
解决
办法1: 重写shouldComponentUpdate()方法
比较新旧state或props数据, 如果有变化才返回true, 如果没有返回false
办法2: 使用PureComponent 【常用】
PureComponent重写了shouldComponentUpdate(), 只有state或props数据有变化才返回true
注意:
只是进行state和props数据的浅比较, 如果只是数据对象内部数据变了, 返回false
不要直接修改state数据(如果是更改数组或是对象,那么不要用内置的方法更改数据), 而是要产生新数据
import React, { Component,PureComponent } from 'react'
import "./index.css"
export default class Parent extends Component {
state={ car:"奔驰C36" }
changeCar=()=>{
this.setState({car:"迈巴赫"});
/* const obj = this.state; // 示例问题:PureCompoent 不要直接修改state数据, 而是要产生新数据。
obj.car = "迈巴赫";
this.setState(obj); */
}
render() {
let { car } = this.state;
console.log("Parent-render")
return (
<div className="parent">
<h1>父组件</h1>
<div>我的车是:{this.state.car} <button onClick={ this.changeCar }>换新车</button></div>
<Child car={car}/>
<Child/>
</div>
)
}
}
class Child extends PureComponent{
render(){
let { car } = this.props;
console.log("Child-render-01")
return(
<div className='child'>
<h2>子组件PureComponent</h2>
<div>爸爸的车是:{car}</div>
</div>
)
}
}
七、 render props 与 children props 【重要】
如何向组件内部动态传入带内容的结构(标签)?
- Vue中:
使用slot技术, 也就是通过组件标签体传入结构<A><B/></A>
- React中:
方式一、children props 通过组件标签体传入结构
<A> <B>xxxx</B> </A>
// 呈现B组件的地方
{this.props.children}
问题: 如果B组件需要A组件内的数据, ==> 做不到
方式二、render props 通过组件标签属性传入结构,而且可以携带数据,一般用render函数属性
<A render={ (data) => <B data={data}/> } />
// 在A组件中呈现B组件的地方: { this.props.render(内部state数据) }
// B组件: 读取A组件传入的数据显示 {this.props.data} - 示例代码:
// 形成父子组件的两种方式:
// 1:在A【组件】内写B标签
// 2:在A【标签】内写B标签,然后在A组件内通过this.props.children获取
// 形如插槽:任意渲染组件、任意传参
import React, { Component } from 'react'
import "./index.css"
export default class index extends Component {
render() {
return (
<div className='parent'>
<h2>父组件</h2>
<A render={ name => <B name={name}/>} />
{/* <A><B /></A> */}
</div>
)
}
}
class A extends Component{
state = {
name:"张三A"
}
render(){
console.log("渲染A",this.props)
const { name } = this.state;
return(
<div className="a">
<h2>我是A组件</h2>
{/* { this.props.children} */}
{ this.props.render(name)}
</div>
)
}
}
class B extends Component{
render(){
console.log("渲染B")
return(
<div className='b'>
<h3>我是B组件</h3>
<div>得到A名字:{this.props.name}</div>
</div>
)
}
}
八、 错误边界 【只适用于生产环境、开发环境短暂显示效果】
(在开发环境中持续时间不长,在生产环境中可正确渲染)
理解:错误边界(Error boundary):用来捕获后代组件错误,渲染出备用页面
特点:只能捕获【后代】组件【生命周期】产生的错误,不能捕获自己组件产生的错误和其他组件在合成事件、定时器中产生的错误
使用方式:getDerivedStateFromError配合componentDidCatch
import React, { Component } from 'react'
import Child from "./Child"
export default class Parent extends Component {
state={
hasError:""
}
// 当Parent的后代组件出现报错,会触发调用,并携带错误信息。
static getDerivedStateFromError(error){
console.log("有错误",error)
return { hasError:error} // 在render之前触发,返回新的state
}
// 报错后续处理
componentDidCatch(error,info){
console.log("统计错误次数,反馈给服务器,用于通知编码人员及时修改Bug",error,info)
}
render() {
return (
<div>
<h2>我是Parent组件</h2>
{this.state.hasError?<h1>服务器异常,请稍后再试</h1>:<Child/>}
</div>
)
}
}
九、 组件通信方式总结 【重要-已消化】
组件间的关系:
- 父子组件
- 兄弟组件(非嵌套组件)
- 祖孙组件(跨级组件)
几种通信方式:
1.props:(1).children props (2).render props
2.消息订阅-发布: pubs-sub、event等等
3.集中式管理: redux、dva等等
4.conText: 生产者-消费者模式
比较好的搭配方式:
父子组件:props
兄弟组件:消息订阅-发布、集中式管理
祖孙组件(跨级组件):消息订阅-发布、集中式管理、conText(开发用的少,封装插件用的多)