天天看点

理解React hooks常用方法useState, useEffect, useMemo, useCallback, useContext

所在项目一直使用ReactNative的 0.58, 积累了大量的业务代码, 

因此一直没有使用React和ReactNative推出的hooks方法编写.

现在自己学习理解一下.

useState

  针对每个state的值设置一组value/setValue.

  值不变的set不会重复触发render.

const [count, setCount] = useState(0);
  <p>You clicked {count} times</p>                 // 获取count值
  <button onClick={() => setCount(count + 1)}>     // 通过setCount设置
    Click Me
  </button>
           

useEffect

  > 生命周期回调: 

    返回值: 可返回一个函数用于消除副作用.

    以生命周期来解释Effect:

      1. Mount: 运行第一次 effect

      2. Update: 清除上一个 effect, 运行下一个 effect   (update可发生多次)

      3. Unmount: 清除最后一个 effect

  > 第二个参数可填一个数组, 也可以不填.

    表示某几个state中有一个变化, 就触发update的Effect调用.

useEffect(() => {
      if (!oldTitle) oldTitle = document.title;            // 记下原标题
      document.title = `You clicked ${count} times`;       // 副作用, 更改标题
      return function cleanup() {
        document.title = oldTitle;                         // 消除副作用, 还原标题    
      };
    }, [count]);                                           // count变化才触发, 可不填
           

useContext

  context可以用于跨越多层传递参数, 

  在多层情况下, 相比props一层一层的传递更有效.

const themes = {                                                          // 创建两组主题样式
    light: { color: "#000000", background: "#eeeeee" },
    dark: { color: "#ffffff", background: "#222222" }
  };
  const ThemeContext = React.createContext(themes.light);                   // 创建Context的类型
  <ThemeContext.Provider value={count % 2 ? themes.dark : themes.light}>    // 建Context节点
    <ThemedButton />
  </ThemeContext.Provider>
  function ThemedButton() {
    const theme = useContext(ThemeContext);
    return <button style={theme}>styled by context!</button>;
  }
           

useReducer

  替换useState, 类似redux的用法和功能.

const initialState = {count: 0};                                  // state初始值
  function reducer(state, action) {                                 // reducer处理dispatch
    switch (action.type) {
      case 'increment': return {count: state.count + 1};            // 生成新的state
      default: throw new Error();
    }
  }
  const [state, dispatch] = useReducer(reducer, initialState);      // userReducer返回state,dispatch
  state.count                                                       // 使用state中的value
  <button onClick={() => dispatch({type: 'decrement'})}>-</button>  // 使用dispatch
           

useRef

访问节点的ref对象

function TextInputWithFocusButton() {
    const inputEl = useRef(null);                          // 创建初始null的ref
    return <>
      <input ref={inputEl} type="text" />                  // 获取ref
      <button onClick={() => {
        inputEl.current.focus();                           // 使用ref对象的函数
      }}>Focus</button>
    </>
  }
           

userCallback

数据变化才更新, 比对第二个参数

const renderButton = useCallback(
    () => <Button > {xxx} </Button>,
    [xxx]
  );
           

useMemo

数据变化才做调用, 避免不必要的执行大量计算, 比对第二个参数

  const result = useMemo(
  () => {
    ...         // 大量计算
  }, [xxx]);
           

参考链接

https://react.docschina.org/docs/hooks-reference.html