React 常用的扩展知识点

setState 更新状态时异步的。而且他每次更新都会重新渲染数据。 即便是给setState({})传入空对象。还是会触发数据更新 --> dom 更新

一、React 状态更新函数setState 的两种方式

注意callback回调函数是可选的,他在状态更新完毕后,render 渲染后 才来调用callback函数。

  • 对象方式的setState
setState({name: 'example'}, () => {
  console.log()
})
  • 函数方式的setState
    update更新函数会接收到state,和props
setState((state,props) => {
  state.name = 'fnUpdate';
}, () => {
  console.log('do something')
})

两者间的区别
对象类型的setState 是函数setState的简写或者是语法糖
1、如果新状态不依赖于旧状态 =====> 使用对方方式
2、如果新状态依赖于原状态 =======> 使用函数方式
3、如果想在状态更新后(setState)获取到最新的状态数据,则要在callback回调函数里面获取。

二、React lazyLoad 组件懒加载

1、通过React的lazy()函数 + 配合import() 来动态加载路由组件, 路由组件代码在构建打包的时候会被拆分出来,单独打包。

const Login = lazy(() => import('@/components/login'))

2、通过suspense 组件指定在加载得到路由打包文件前显示自定义一个 loading 界面。

<Suspense fallback={<h1> ...loading </h1>}>
  <Routes>
    <Route path="/home/index" element="<Login/>"></Route>
    <Redrict to="/login" />
  </Routes>
</Suspense>

三、React Context 容器对象 用以多层嵌套的后代组件间的通信 React Context 官方文档

1、创建 Context 容器对象

export const themes = {
  light: {
    foreground: '#000000',
    background: '#eeeeee',
  },
  dark: {
    foreground: '#ffffff',
    background: '#222222',
  },
};
const MYContext = React.createContext(themes.light)

2、渲染子组件,用 <MYContext.Provide></MYContext.Provide>包裹组件 ,通过value属性给后代组件传递数据。

import themes from '../data/themes'
class App extends React.Component {
  state = {
    theme: themes.light
  }
  render(){
    return (<div>
      <MYContext.Provider value={this.state.theme}>
        <ThemedButton />
      </MYContext.Provider>
    </div>)
  }
}

3、 如果是类组件,如下所示

class App extends React.Component {
  static contextType = MYContext
  render(){
    return (<div>{ this.context }</div>)
  }
}

4、后代组件读取数据 <Context.Consumer></Context.Consumer>

class ThemedButton  extends React.Component {
  return (<MYContext.Consumer>
    {
      (context) => (<div>{context.theme}</div>) 
    }
  </MYContext.Consumer>)
}

四、React Conponent 组件优化

React 类组件 一般都是继承 React.Component , 在组件嵌套的时候会出现,子组件虽然嵌套在父组件里面。但是子组件并没有使用父组件传的state和props 属性。但是父组件更新了。子组件也会更新。

解决方法
1、重写 React的数据更新的生命周期函数,shouldComponentUpdate((state, props) => {}) , 比较新旧 state,和props值, 如果有变化才返回true, 否则返回false。
2、组件继承 pureComponent 该组件已经内置了shouldComponentUpdate()函数,他会自动判断新旧值。减少组件的频繁更新,从而优化性能。

五、RenderProps 类似于Vue的插槽

1、children props ====> 通过组件标签体传入xml结构, 子组件通过 {{this.props.children}} 来获取到组件内部传过来的结构

<FirstComponent>
  <SecondComponent>这是组件First的数据</SecondComponent>
</FirstComponent>

class SecondComponent extends React.Component {
  render(<div>{this.props.children}</div>)
}

2、render props ====> 通过组件标签属性传入xml结构, 一般用于render函数属性, 可以通过props.render() 方法把数据传递给子组件。

<FirstComponent render={ (renderProps) => (<SecondComponent data={renderProps}/>) }></FirstComponent>

class FirstComponen extends React.Component {
  state = {
    name: 'render 数据' 
  }
  render(<div>{this.props.render(this.state.name)}</div>)
}
posted @ 2022-08-12 20:22  boygdm  阅读(40)  评论(0编辑  收藏  举报