react hooks 学习. FAQ
useState代替state
1 2 3 4 5 6 7 8 9
| function Example(){ const [ count , setCount ] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={()=>{setCount(count+1)}}>click me</button> </div> ) }
|
useEffect代替常用生命周期函数
实现类似componentWillUnmount的效果,useEffect的第二个参数,它是一个数组,数组中可以写入很多状态对应的变量,意思是当状态值发生变化时,我们才进行解绑。但是当传空数组[]时,就是当组件将被销毁时才进行解绑,这也就实现了componentWillUnmount的生命周期函数
1 2 3 4 5 6
| useEffect(()=>{ return ()=>{ } },[])
|
useContext 让父子组件传值更简单
useContext
跨越组件层级直接传递变量,实现共享
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const CountContext = createContext()
function Parent(){ const [ count , setCount ] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={()=>{setCount(count+1)}}>click me</button> <CountContext.Provider value={count}> <Child /> </CountContext.Provider>
</div> ) } function Child() { const count = useContext(CountContext) return <h2>{count}</h2> }
|
useReducer完成类似的Redux
useReducer可以让代码具有更好的可读性和可维护性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function ReducerDemo(){ const [ count , dispatch ] =useReducer((state,action)=>{ switch(action){ case 'add': return state+1 case 'sub': return state-1 default: return state } },0) return ( <div> <h2>现在的分数是{count}</h2> <button onClick={()=>dispatch('add')}>Increment</button> <button onClick={()=>dispatch('sub')}>Decrement</button> </div> )
}
|
待续
useCallback
useMemo
useRef
useImperativeHandle
useLayoutEffect
如有问题可联系 Email:afacode@outlook.com 或 微信:afacode