V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
iugo
V2EX  ›  React

目前我们了解的 React Hooks

  •  
  •   iugo ·
    iugo · 2018-11-29 10:36:54 +08:00 · 1617 次点击
    这是一个创建于 1946 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3235 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:59 · PVG 21:59 · LAX 06:59 · JFK 09:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.