React中的Context API

React中的Context API

zh-hans.reactjs.org/docs/contex…html

  • React.createContextreact

  • Context.Provider => 设置vaue={}数组

  • Class.contextType => 获取context性能优化

  • Context.Consumer =>一样为获取,基于 value=>{…} 获取bash

基于PureComponent进行性能优化

  • 在状态或者属性没有任何更新变化的时候,不渲染组件(帮助咱们实现了 shouldComponentUpdate)ide

  • 浅比较(shallowEqual)性能

  • 对于深层次状态或者属性改变,咱们尽量从新赋值新值(或者forceUpdate)优化

  • PureComponent的最好做为展现组件ui

  • 如有shouldComponentUpdate,则执行它,若没有这个方法会判断是否是PureComponent,如果,进行浅比较spa

React Hook

  • useState
import {useState} from 'react';
function Count() {
  var [state, setState] = useState(0);
  OR
  var [state, setState] = useState(function(){
      //=>惰性初始化
      return 0;
  });
  return (
    <div>
      <div>{state}</div>
      <button onClick={() => { setState(state + 1) }}>点击</button>
    </div>
  );
}
复制代码
  • 原理:
var _state;
function useState(initialState) {
  _state = _state | initialState;
  function setState(state) {
    _state = state;
    //...从新渲染组件
  }
  return [_state, setState];
}
复制代码
  • useEffect

相似于componentDidMount/Update

//=>若是dependencies不存在,那么callback每次render都会执行
//=>若是dependencies存在,只有当它发生了变化callback才会执行
//=>若是dependencies是空数组,只有第一次渲染执行一次
useEffect(() => {
    // do soming
    return ()=>{
        // componentWillUnmount
    }
}, [dependencies]);
复制代码
  • 原理
let prevDependencies;
function useEffect(callback, dependencies) {
  const isChanged = dependencies
    ? dependencies.some((item,index) => item === prevDependencies[index])
    : true;
  /*若是dependencies不存在,或者dependencies有变化*/
  if (!dependencies || isChanged) {
    callback();
    prevDependencies = dependencies;
  }
}
复制代码
  • useReducer
function reducer(state,action){
    switch(action.type){
        case 'ADD':
           return {count:state.count+1}
       default:
            return {count:state.count-1}
   }
}

class Count(){
    const [state,dispatch]=useReducer(reducer,{count:10});
    return <>
        <p>{state.count}</p>
        <button onClick={ev=>{
            dispatch({
                type:'ADD'
            })
        }}>+</button>
        <button onClick={ev=>{
            dispatch({
                type:'MINUS'
            })
        }}>-</button>
    </>
}
复制代码
  • createRef / useRef
let prev;
function Demo(){
    const inputRef = createRef(); //=>{current:xxx}
    //=>每一次视图渲染都会从新生成一个REF(和上一次的不相等:使用useRef进行优化
    //console.log(prev===inputRef); //=>false
   prev=inputRef;
   return <>
        <input ref={inputRef}>
        <button onClick={ev=>{
            inputRef.current.focus();
        }}>聚焦</button>
    </>
}
复制代码
相关文章
相关标签/搜索