本文开始讲述useRef、useCallback、useContext、useReducer
useReducer
- useReducers()钩子用来引入 Reducer 功能。
- 使用方法如下:
import React,{useReducer} from 'react';
// 定义reducer
const myReducer = (state, action) => {
switch(action.type) {
case('countUp'):
return {
...state,
count: state.count + 1
}
default:
return state
}
}
const UserReducer = () => {
// useReducer使用
const [state, dispatch] = useReducer(myReducer, { count: 0 })
return (
<div className="App">
<!--直接使用dispatch方法-->
<button onClick={() => dispatch({ type: 'countUp' })}>
+1
</button>
<p>Count: {state.count}</p>
</div>
);
}
export default UserReducer;
useContext
- 实现组件间状态共享
- 使用方法如下:
import React,{useContext} from 'react';
// React.createContext创建上下文
const AppContext = React.createContext({})
// 定义AAA组件,使用useContext包裹AppContext,此时username处于组件共享
const AAA = () => {
const { username } = useContext(AppContext)
return (
<div>
AAA- {username}
</div>
)
}
// 定义BBB组件,使用useContext包裹AppContext,此时username处于组件共享
const BBB = () => {
const { username } = useContext(AppContext)
return (
<div>
BBB- {username}
</div>
)
}
const UseContext = () => {
return (
<!--使用Proovider-->
<AppContext.Provider value={{
username: 'xiaoming'
}}>
<div className="App">
<AAA />
<BBB />
</div>
</AppContext.Provider>
)
}
export default UseContext;
useRef
- useRef用来获取dom
- 使用方法如下:
import React,{useRef,useEffect} from 'react';
// 获取焦点
const UseRef = () => {
let inputRef = useRef(null)
useEffect(() => {
inputRef.current.focus()
})
return (
<input type="text" ref={inputRef} />
)
}
export default UseRef;
useCallback
- 可以认为是对依赖项的监听,把接受一个回调函数和依赖项数组,返回一个该回调函数的memoized(记忆)版本,该回调函数仅在某个依赖项改变时才会更新。
import React,{useCallback,useState} from 'react';
const UseCallback = () => {
// useCallback可以认为是对依赖项的监听,把接受一个回调函数和依赖项数组,返回一个该回调函数的memoized(记忆)版本,该回调函数仅在某个依赖项改变时才会更新。
const [count, setCount] = useState(1);
const [num, setNum] = useState(1);
const memoized = useCallback(() => {
return num;
},[count]) // 只有count改变,才会更新
console.log('记忆:',memoized())
console.log('原始:',num)
return (
<>
<button onClick={() => {setCount(count+1)}}>count +</button>
<button onClick={() => {setNum(num+1)}}>num+</button>
</>
)
}
export default UseCallback;