【React自学笔记04】React一些扩展Tips

React扩展用法

1. setState

setState更新状态的2种写法

1️⃣ setState(stateChange, [callback])------对象式的setState

(1)stateChange为状态改变对象(该对象可以体现出状态的更改)

(2)callback是可选的回调函数, 它在状态更新完毕、界面也更新后(render调用后)才被调用

2️⃣ setState(updater, [callback])------函数式的setState

(1)updater为返回stateChange对象的函数

(2)updater可以接收到state和props。(state可以获取原来的状态值)

(3)callback是可选的回调函数, 它在状态更新、界面也更新后(render调用后)才被调用。

import React, { Component } from 'react'
export default class Demo extends Component {
  state = {
    count: 0
  }
  add = () => {
    /*对象式setState:
    setState是一个同步方法,由React主线程调用
    setState引起React后续动作是异步的(状态更新是异步的)
    回调调用的时机是React改完状态、调完render后再调回调
    */
    this.setState({ count: this.state.count + 1 }, () => {
      console.log(this.state.count);
    })
      
    /*函数式setState简写:
    this.setState(state => {( { count: state.count + 1 })
    })
    */
    this.setState((state, props) => {
      console.log(state, props);
      return { count: state.count + 1 }
    })
  }
  render() {
    return (
      <div>
        <h1>当前求和为:{this.state.count}</h1>
        <button onClick={this.add}>点我加一</button>
      </div>
    )
  }
}

💕 总结:

  1. 对象式的setState是函数式的setState的简写方式(语法糖)

  2. 使用原则:

     (1).如果新状态不依赖于原状态 ===> 使用对象方式
    
     (2).如果新状态依赖于原状态 ===> 使用函数方式
    
     (3).如果需要在setState()执行后获取最新的状态数据, 要在第二个callback函数中读取
    

2. lazyLoad

路由组件的lazyLoad

使用路由v5版本案例

在引入路由组件的文件中写如下代码:

import {lazy,Suspense} from 'react'	
//1.通过React的lazy函数配合import()函数动态加载路由组件 ===> 路由组件代码会被分开打包
const Login = lazy(()=>import('@/pages/Login'))
	
//2.通过<Suspense>指定在加载得到路由打包文件前显示一个自定义loading界面
//<Suspense>标签包裹注册路由 并指定fallback定义加载过程中显示的组件
<Suspense fallback={<h1>loading.....</h1>}>
  <Switch>
    <Route path="/xxx" component={Xxxx}/>
    <Redirect to="/login"/>
  </Switch>
</Suspense>

3. Hooks

3.1 React Hook/Hooks

  1. Hook是React 16.8.0版本增加的新特性/新语法

  2. 可以让你在函数组件中使用 state 以及其他的 React 特性

3.2 三个常用的Hook

  1. State Hook: React.useState()

  2. Effect Hook: React.useEffect()

  3. Ref Hook: React.useRef()

3.3 State Hook

  • State Hook让函数组件也可以有state状态, 并进行状态数据的读写操作

  • 语法: const [xxx, setXxx] = React.useState(initValue)

  • useState()说明:

    • 参数: 第一次初始化指定的值在内部作缓存

    • 返回值: 包含2个元素的数组, 第1个为内部当前状态值, 第2个为更新状态值的函数

  • setXxx()2种写法:

    • setXxx(newValue): 参数为非函数值, 直接指定新的状态值, 内部用其覆盖原来的状态值

    • setXxx(value => newValue): 参数为函数, 接收原本的状态值, 返回新的状态值, 内部用其覆盖原来的状态值

import React from 'react'

export default function Demo() {
  const [count, setCount] = React.useState(5)
  const [name, setName] = React.useState('tom')
  function add() {
    setCount(count + 1)
  }
  function changeName() {
    setName('jack')
  }
  return (
    <div>
      <h1>当前求和为{count}</h1>
      <h1>当前名字为{name}</h1>
      <button onClick={add}>点我加一</button>
      <button onClick={changeName}>点我改名</button>
    </div>
  )
}

3.4 Effect Hook

  • Effect Hook 可以在函数组件中执行副作用操作(用于模拟类组件中的生命周期钩子)

  • React中的副作用操作:

    • 发ajax请求数据获取

    • 设置订阅 / 启动定时器

    • 手动更改真实DOM

  • 语法和说明:

  useEffect(() => { 
            // 在此可以执行任何带副作用操作
            return () => { // 在组件卸载前执行
              // 在此做一些收尾工作, 比如清除定时器/取消订阅等,相当于componentWillUnmount() 
            }
  }, [stateValue]) // 如果指定的是[], 回调函数只会在第一次render()后执行
  • 数组中指定参数时,类似于vue中的watch监测数据变化

  • 数组为空时,谁也不监测,类似于componentDidMount()生命周期钩子

  • 不传第二个参数,相当于监测所有数据

  • 可以把 useEffect Hook 看做如下三个函数的组合

    • componentDidMount()
    • componentDidUpdate()
    • componentWillUnmount()
import React from 'react'
import { createRoot } from 'react-dom/client'
export default function Demo() {
  const [count, setCount] = React.useState(0)
  const [name, setName] = React.useState('tom')
  function add() {
    setCount(count + 1)
  }
  function changeName() {
    setName('jack')
  }
  React.useEffect(() => {
    const timer = setInterval(() => {
      setCount(count => count + 1)
      // setCount(count + 1)为什么无法正确出现效果
    }, 1000)
    return () => {
      clearInterval(timer)
    }
  }, [])
  function unMount() {
    // ReactDOM.unmountComponentAtNode(document.getElementById('root'))
    const root = createRoot(document.getElementById('root'));
    root.unmount()
  }
  return (
    <div>
      <h1>当前求和为{count}</h1>
      <h1>当前名字为{name}</h1>
      <button onClick={add}>点我加一</button>
      <button onClick={changeName}>点我改名</button>
      <button onClick={unMount}>卸载组件</button>
    </div>
  )
}

3.5 Ref Hook

  • Ref Hook可以在函数组件中存储/查找组件内的标签或任意其它数据

  • 语法: const refContainer = useRef()

  • 作用:保存标签对象,功能与React.createRef()一样

import React from 'react'
export default function Demo() {
  const myRef=React.useRef()

  function showData(){
    alert(myRef.current.value)
  }
  
  return (
    <div>
      <input type="text" ref={myRef}/>
      <button onClick={showData}>点我提示数据</button>
    </div>
  )
}

4. Fragment

< Fragment>< /Fragment>或者使用空标签<></>

Fragment可以参与遍历,定义唯一key值

import React, { Fragment } from 'react'
export default function index() {
  return (
    <Fragment key={1}>index</Fragment>
  )
}

可以不用必须有一个真实的DOM根标签了

Fragment在编译时会被丢失


5. Context

一种组件间通信方式, 常用于【祖组件】与【后代组件】间通信

5.1 使用

  • 创建Context容器对象:const XxxContext = React.createContext()

  • 渲染子组时,外面包裹xxxContext.Provider, 通过value属性给后代组件传递数据:

    <xxxContext.Provider value={数据}>
      子组件
    </xxxContext.Provider>
    
  • 后代组件读取数据:

    //第一种方式:仅适用于类组件 
    static contextType = xxxContext  // 声明接收context
    this.context // 读取context中的value数据
    	  
    //第二种方式: 函数组件与类组件都可以
    <xxxContext.Consumer>
    {
    	value => ( // value就是context中的value数据
    	  要显示的内容
    	)
    }
    </xxxContext.Consumer>
    
  • 注意:在应用开发中一般不用context, 一般都用它的封装react插件

5.2 代码示例

//第一种方式:类组件
import React, { Component } from 'react'

const MyContext = React.createContext()
const { Provider } = MyContext

export default class A extends Component {
  state = { username: 'tom', age: 18 }
  render() {
    const { username, age } = this.state
    return (
      <div>
        <h1>我是A组件</h1>
        <h2>我的用户名是{username}</h2>
        {/* 省略写法 {{username,age}} */}
        <Provider value={{ username: username, age: age }}>
          <B />
        </Provider>
      </div>
    )
  }
}
class B extends Component {
  render() {
    return (
      <div>
        <h1>我是B组件</h1>
        <C />
      </div>
    )
  }
}
class C extends Component {
  // 声明接收
  static contextType = MyContext
  render() {
    const { username, age } = this.context
    return (
      <div>
        <h1>我是C组件</h1>
        <h2>我从A组件接收的用户名{username},年龄{age}</h2>
      </div>
    )
  }
}
//第二种方式: 函数组件与类组件都可以
const { Provider, Consumer } = MyContext
function C() {
  return (
    <div>
      <h1>我是C组件</h1>
      <h2>我从A组件接收的用户名</h2>
      <Consumer>
        {
          value => {
            return `${value.username},年龄是${value.age}`
          }
        }
      </Consumer>
    </div>
  )
}

6. 组件优化

Component的2个问题

  • 只要执行setState(),即使不改变状态数据, 组件也会重新render() ==> 效率低
  • 只当前组件重新render(), 就会自动重新render子组件,即使子组件没有用到父组件的任何数据 ==> 效率低

效率高的做法

  • 只有当组件的state或props数据发生改变时才重新render()

  • 原因Component中的shouldComponentUpdate()总是返回true

解决

办法1: 
	重写shouldComponentUpdate()方法
	比较新旧state或props数据, 如果有变化才返回true, 如果没有返回false
办法2:  
	使用PureComponent
	PureComponent重写了shouldComponentUpdate(), 只有state或props数据有变化才返回true
	注意: 
		只是进行state和props数据的浅比较, 如果只是数据对象内部数据变了, 返回false  
		不要直接修改state数据, 而是要产生新数据
项目中一般使用PureComponent来优化

回顾:在[react]开发中,经常需要对数据state状态进行改变,但是这种方式每当setState的时候都会将所有的组件重新渲染一遍,这样就会有重复渲染render的问题。实现shouldComponentUpdate()函数可以用来指明在什么样的确切条件下,这个组件得到重绘。

//方法一:重写shouldComponentUpdate方法,只有数据发生变化时组件才进行重绘
import React, { Component } from 'react'

export default class Parent extends Component {
  state = { carName: '奥迪' }
  changeCar = () => {
    // this.setState({ carName: '奔驰' })
    this.setState({})
  }
  shouldComponentUpdate(nextProps, nextState) {
    console.log(this.props, this.state);
    console.log(nextProps, nextState);
    if (this.state.carName === nextState.carName) return false
    return true;
  }
  render() {
    const { carName } = this.state
    console.log('parent render');
    return (
      <div>
        <h1>我是parent组件</h1>
        <h3>我的车名是{carName}</h3>
        <button onClick={this.changeCar}>换车</button>
      </div>
    )
  }
}

父组件调用了子组件,但是子组件没有用到父组件的任何数据时

  • 孩子不需要任何状态,更关注props
  • 在孩子组件中也重写shouldComponentUpdate()函数
import React, { Component } from 'react'

export default class Parent extends Component {
  state = { carName: '奥迪' }
  changeCar = () => {
    this.setState({ carName: '奔驰' })
    // this.setState({})
  }
  shouldComponentUpdate(nextProps, nextState) {
    // console.log(this.props, this.state);
    // console.log(nextProps, nextState);
    return !(this.state.carName === nextState.carName)
  }
  render() {
    const { carName } = this.state
    console.log('parent render');
    return (
      <div>
        <h1>我是parent组件</h1>
        <h3>我的车名是{carName}</h3>
        <button onClick={this.changeCar}>换车</button>
        {/* <Child carName={carName} /> */}
        <Child />
      </div>
    )
  }
}

class Child extends Component {
  shouldComponentUpdate(nextProps, nextState) {
    console.log(this.props, this.state);
    console.log(nextProps, nextState);
    return !this.props.carName === nextProps.carName
  }
  render() {
    console.log('child render');
    // const { carName } = this.props;
    return (
      <div>
        <h1>我是children组件</h1>
        {/* <h3>我收到的车名是{carName}</h3> */}
      </div>
    )
  }
}

真正开发时,不需要自己手动实现,使用PureComponent底层已经自动实现上述逻辑

注意如果使用PureComponent,那么更新的状态对象要确保和之前的对象不发生关联,不是同一个对象

import React, { PureComponent } from 'react'
export default class Parent extends PureComponent {
  state = { carName: '奥迪' }
  changeCar = () => {
    // this.setState({ carName: '奔驰' })
    this.setState({})
  }
  render() {
    const { carName } = this.state
    console.log('parent render');
    return (
      <div>
        <h1>我是parent组件</h1>
        <h3>我的车名是{carName}</h3>
        <button onClick={this.changeCar}>换车</button>
        <Child carName={carName} />
        {/* <Child /> */}
      </div>
    )
  }
}
class Child extends PureComponent {
  render() {
    console.log('child render');
    const { carName } = this.props;
    return (
      <div>
        <h1>我是children组件</h1>
        <h3>我收到的车名是{carName}</h3>
      </div>
    )
  }
}

7. render props

如何向组件内部动态传入带内容的结构(标签)?

Vue中: 
	使用slot技术, 也就是通过组件标签体传入结构  <A><B/></A>
React中:
	使用children props: 通过组件标签体传入结构
	使用render props: 通过组件标签属性传入结构,而且可以携带数据,一般用render函数属性

children props

<A>
  <B>xxxx</B>
</A>
{this.props.children}
问题: 如果B组件需要A组件内的数据, ==> 做不到 

render props

<A render={(data) => <C data={data}></C>}></A>
A组件: {this.props.render(内部state数据)}
C组件: 读取A组件传入的数据显示 {this.props.data} 

完整代码示例:

import React, { Component } from 'react'

export default class Parent extends Component {
  render() {
    return (
      <div>
        <h3>我是parent组件</h3>
        <A render={(name) => <B name={name} />}></A>
      </div>
    )
  }
}
class A extends Component {
  state = { name: 'tom' }
  render() {
    const { name } = this.state
    return (
      <div>
        <h3>我是A组件</h3>
        {this.props.render(name)}
      </div>
    )
  }
}
class B extends Component {
  render() {
    const { name } = this.props;
    return (
      <div>
        <h2>我是B组件,我收到的名字是{name}</h2>
      </div>
    )
  }
}

打包:npm run build

上线:安装第三方服务器:npm i serve -g

运行:serve build


8. 错误边界

理解:

错误边界(Error boundary):用来捕获后代组件错误,渲染出备用页面

特点:

只能捕获后代组件生命周期产生的错误,不能捕获自己组件产生的错误和其他组件在合成事件、定时器中产生的错误

使用方式:

getDerivedStateFromError配合componentDidCatch

// 生命周期函数,一旦后台组件报错,就会触发
static getDerivedStateFromError(error) {
    console.log(error);
    // 在render之前触发
    // 返回新的state
    return {
        hasError: true,
    };
}

componentDidCatch(error, info) {
    // 统计页面的错误。发送请求发送到后台去
    console.log(error, info);
}

9. 组件通信方式总结

组件间的关系:

  • 父子组件
  • 兄弟组件(非嵌套组件)
  • 祖孙组件(跨级组件)

几种通信方式:

	1.props:
		(1).children props
		(2).render props
	2.消息订阅-发布:
		pubs-sub、event等等
	3.集中式管理:
		redux、dva等等
	4.conText:
		生产者-消费者模式

比较好的搭配方式:

	父子组件:props
	兄弟组件:消息订阅-发布、集中式管理
	祖孙组件(跨级组件):消息订阅-发布、集中式管理、conText(开发用的少,封装插件用的多)

——————————本章笔记完成于2022.5.29——————————

posted @ 2022-05-26 17:47  Lu西西  阅读(96)  评论(0)    收藏  举报