gaowei1012 / blog

this is blog
2 stars 0 forks source link

react hooks 重构 Class 组件 #55

Open gaowei1012 opened 3 years ago

gaowei1012 commented 3 years ago

首先来大概介绍下 react hooks 的一些常用的

  const handleClick = useCallback(() => {
     // ...
  })
gaowei1012 commented 3 years ago

统一处理原先定的 state 数据

// 省略非关键代码....
 const [value, setValue] = useState('');
 const [isShow, setIsShow] = useState(false);
 const [history, setHistory] = useState([{name: '热门土地'}]);
// 省略非关键代码...
gaowei1012 commented 3 years ago

使用 useEffect

useEffect(() => {
  // 获取数据 && 处理业务
},[])

如果要在 useEffect 如果处理异步的话,不能这样做

useEffect( async () => {
    const result = await request('url')
    // todo
}, [])

要这样做

useEffect(() => {
   const result = async=()=> {
      await request('url')
   }

  result()
}, [])
gaowei1012 commented 3 years ago

使用 useRef

let inputRef = useRef(null)

// DOM
<input type='text' ref={inputRef} />

const editInputValue =()=> {
  let val = inputRef.current.value
  console.log(val)
  /// do val...
}
gaowei1012 commented 3 years ago

使用 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>
   )
}