iugo
V2EX  ›  React

目前我们了解的 React Hooks

  •  
  •   iugo ·
    iugo · Nov 29, 2018 · 2158 views
    This topic created in 2747 days ago, the information mentioned may be changed or developed.

    React Hooks

    什么是 React Hooks?

    React Hooks 是一套新的管理 React state 的机制, 不需要使用 JavaScript class 的写法, 而是以函数组件的方式, 但却可以管理 state.

    React Hooks 为什么重要?

    首先, 在 React Conf 2018 中, React Hooks 是唯一重要的事情. 虽然 @dan_abramov 告诉我们不需要重写之前的 class 组件, 但这句话似乎是在说, 新的组件用 Hooks 来写吧. @ryanflirence 说的更彻底, 你要把之前的 class 组件重写一遍.

    其次, 在 React Doc https://reactjs.org/docs/hooks-intro.html 中, Hooks 被单独拿来作为一个章节.

    虽然现在只是一项提案, 但它代表着 React 的未来. 参考在 https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889 中, Dan 说到这么一句话: This is why Hooks represent our vision for the future of React.

    个人认为, 它可能会像 JSX 一样, 虽然又是一个新造的概念, 但好用.

    Hooks 的作用

    Hooks 让 React 更加清晰的定位单向数据流渲染.

    React 接收并可以实时处理三种变量:

    1. props
    2. state
    3. other

    class 可以保有自己的 state, 也可以通过生命周期函数将 other 赋在 state 上.

    而 Hooks, 使用 useState 和 useEffect 代替了 class.

    对 class 对比

    替代 setState

    [value, setValue] = useState(initValue)
    

    替代 componentDidMount

    useEffect(
      () => {
        // componentDidMount
      },
      [],
    );
    

    替代 componentWillUnmount

    useEffect(
      () => {
        return // componentWillUnmount
      },
      [],
    );
    

    替代 componentDidUpdate

    useEffect(
      () => {
        // componentDidUpdate && componentDidMount
      },
    );
    

    文档

    https://reactjs.org/docs/hooks-reference.html

    ref: https://github.com/zsqk/zsqk/issues/100

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2842 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 04:29 · PVG 12:29 · LAX 21:29 · JFK 00:29
    ♥ Do have faith in what you're doing.