useState()
useState用法
用法:传入一个参数作为状态的初始值,返回两个值,第一个是当前状态的熟悉,第二个是修改状态的方法
const [value, setValue] = useState(initialValue)
useState实现原理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| let memoizedStates = [] let index = 0 function useState (initialState) { memoizedStates[index] = memoizedStates[index] || initialState let currentIndex = index function setState (newState) { memoizedStates[currentIndex] = newState render() } return [memoizedStates[index++], setState] }
function render() { index = 0 ReactDOM.render(<Counter />, document.getElementById('root')); }
|
useEffect()
useEffect用法
useEffect() 接受两个参数,第一个为执行函数,第二个为依赖项数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
const [value, setValue] = useState(initialValue)
useEffect(()=>{ })
useEffect(()=>{ },[])
useEffect(()=>{ },[value])
useEffect(()=>{ return ()=>{ } },[value])
|
useRef()
useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内保持不变。
- 获取真实DOM
- 记录组件更新之前的值
1 2 3 4 5 6 7 8 9 10 11 12 13
| function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
|