setState更新状态的2种写法
1.stateChange为状态改变对象(该对象可以体现出状态的更改)
2.callback是可选的回调函数, 它在状态更新完毕、界面也更新后(render调用后)才被调用
this.setState(
{count:++count},
()=>{console.log("render执行后的回调",this.state.count)}
);
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)}
)
路由组件的lazyLoad
//1.通过React的lazy函数配合import()函数动态加载路由组件 ===> 路由组件代码会被分开打包
const Login = lazy(()=>import('@/pages/Login'))
//2.通过``````指定在加载得到路由打包文件前显示一个自定义loading界面
<Suspense fallback={<h1>loading.....</h1>}>
<Switch>
<Route path="/xxx" component={Xxxx}/>
<Redirect to="/login"/>
</Switch>
</Suspense>
(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>
)
}
useEffect(() => {
// 在此可以执行任何带副作用操作
return () => { // 在组件卸载前执行
// 在此做一些收尾工作, 比如清除定时器/取消订阅等
}
}, [stateValue]) // 如果指定的是[], 回调函数只会在第一次render()后执行 注意:第二个参数不写全检测、[]:都不检测,[count]只检测count
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>
)
}
(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>
)
}
使用:
与 <>>
作用:可以不用必须有一个真实的DOM根标签了。
区别:
Fragment标签只能有一个标签属性【key】;若再写其他标签属性就会报错。
<>不能接受键值或属性。
理解:一种组件间通信方式, 常用于【祖组件】与【后代组件】间通信
使用:
const XxxContext = React.createContext()
<xxxContext.Provider value={数据}>
子组件
</xxxContext.Provider>
//第一种方式:仅适用于类组件
static contextType = xxxContext // 声明接收context
this.context // 读取context中的value数据
//第二种方式: 函数组件与类组件都可以
<xxxContext.Consumer>
{ value => () } // value就是context中的value数据要显示的内容
</xxxContext.Consumer>
注意:在应用开发中一般不用context, 一般都用它的封装react插件
Component的2个问题
原因: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>
)
}
}
如何向组件内部动态传入带内容的结构(标签)?
xxxx
} />
// 形成父子组件的两种方式:
// 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}/>} />
{/* */}
</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(开发用的少,封装插件用的多)