Open gaowei1012 opened 3 years ago
统一处理原先定的 state
数据
// 省略非关键代码....
const [value, setValue] = useState('');
const [isShow, setIsShow] = useState(false);
const [history, setHistory] = useState([{name: '热门土地'}]);
// 省略非关键代码...
使用 useEffect
useEffect(() => {
// 获取数据 && 处理业务
},[])
如果要在 useEffect
如果处理异步的话,不能这样做
useEffect( async () => {
const result = await request('url')
// todo
}, [])
要这样做
useEffect(() => {
const result = async=()=> {
await request('url')
}
result()
}, [])
使用 useRef
let inputRef = useRef(null)
// DOM
<input type='text' ref={inputRef} />
const editInputValue =()=> {
let val = inputRef.current.value
console.log(val)
/// do val...
}
使用 useReducer
;在 useState
中使用的 useReducer
实现的,有时候在初始化面数据的时候,我们可以使用 useRedcuer
来编写一些更复杂的逻辑
const initialState = 0
const reducer = (state, action) => {
switch() {
case 'incerment':
return {number: state.number + 1}
case 'decreemnt':
return {number: state.number - 1}
default:
throw new Error()
}
}
const init =(initialState)=> {
return {number: initialState}
}
const Counter =()=> {
const [state, dispatch] = useReducer(reducer, initialState, init)
return (
<div>{state}</div>
)
}
首先来大概介绍下
react hooks
的一些常用的useState 初始化组件
state
, 类似state = { // todo }
具体使用会定义在在函数组件的最顶部,回去加载初始化,举个🌰useEffect 组件加载在中调用,相当于类组件中的
componentDidMount && componentDidUpdate
等生命周期函数,此时我们的DOM
节点已经加载完毕,可以去做网络请求等相关工作。 举个🌰注意,此钩子接收两个参数,第一个是
callback
用于处理我们的业务数据,第二个参数用于优化,也就是组价刷新所依赖的对象useCallback 此钩子接收一个
callback
用于定义我们的回调函数DOM
节点,以供我们操作使用