useState
useState 让函数式组件拥有状态
state 只有在第一次渲染时被创建,之后每次重新渲染都在复用这个 state
setState 可以像在 class 组件里一样传入函数,实现同步更新
import React, { useState } from 'react';
export default function Count() {
const [count, setCount] = useState(0)
return <div>
<div>{count}</div>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount((preValue) => preValue - 1)}>-1</button>
</div>;
}
useEffect和useContext
参看文档:https://www.yuque.com/venivici/grlnzp/wsq1to
useReducer
useReducer 只是 useState 的替代,并不是 redux 的替代
不过 useReducer 和 useContext 一起使用可以实现轻量级状态管理取代 redux
import React, { useReducer } from 'react';
const reducer = (state, action) => {
switch(action.type) {
case 'increment':
console.log(action.payload)
return {...state, count: state.count + action.payload}
case 'decrement':
return {...state, count: state.count - action.payload}
default:
return state
}
}
export default function CounterWithReducer() {
const [state, dispatch] = useReducer(reducer, {count: 0})
return <div>
<div>{state.count}</div>
<button onClick={() => dispatch({type:'increment', payload:2})}>+2</button>
<button onClick={() => dispatch({type:'decrement', payload:1})}>-1</button>
</div>;
}
useCallback 和 useMemo
参考文档:https://www.yuque.com/venivici/grlnzp/tneidp
useRef
参考文档:https://www.yuque.com/venivici/grlnzp/ipbwnz
forwardRef 和 useImperativeHandle
参考文档:
https://www.yuque.com/venivici/grlnzp/tneidp
https://www.yuque.com/venivici/grlnzp/lo1tfy