React中的Context API

538 阅读1分钟

React中的Context API

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

  • React.createContext

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

  • Class.contextType => 获取context

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

基于PureComponent进行性能优化

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

  • 浅比较(shallowEqual)

  • 对于深层次状态或者属性改变,我们尽可能重新赋值新值(或者forceUpdate)

  • PureComponent的最好作为展示组件

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

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>
    </>
}