zh-hans.reactjs.org/docs/contex…html
React.createContextreact
Context.Provider => 設置vaue={}數組
Class.contextType => 獲取context性能優化
Context.Consumer =>一樣爲獲取,基於 value=>{…} 獲取bash
在狀態或者屬性沒有任何更新變化的時候,不渲染組件(幫助咱們實現了 shouldComponentUpdate)ide
淺比較(shallowEqual)性能
對於深層次狀態或者屬性改變,咱們儘量從新賦值新值(或者forceUpdate)優化
PureComponent的最好做爲展現組件ui
如有shouldComponentUpdate,則執行它,若沒有這個方法會判斷是否是PureComponent,如果,進行淺比較spa
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];
}
複製代碼
相似於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;
}
}
複製代碼
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>
</>
}
複製代碼
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>
</>
}
複製代碼