React手稿之State Hooks of Hooks

React Hooks

React在16.7.0-alpha.0版本中提到了Hooks的概念,目前仍是Proposal阶段。react

官方也陈述,接下来的90%的工做会投入到React Hooks中。git

从目前官方的文档能够看出,Hooks从如下四个方面来提升React的编码。github

  • state
  • 生命周期
  • content
  • 自定义方法

Hooks的主要用途是替代以前版本的 class 组件。npm

说明:bash

到目前为止,React在已发布的release版本中有该功能,想体验该功能,必须安装16.7.0-alpha.0。dom

npm i react@16.7.0-alpha.0 react-dom@16.7.0-alpha.0

//或者

yarn add react@16.7.0-alpha.0 react-dom@16.7.0-alpha.0

State Hooks

首先看一个React既有的版本基于 class 的组件.this

import React from 'react';

class Counter extends React.Component {
  constructor(props) {
    super(props);

    this.state = { count: 0 };
  }

  render() {
    const { count } = this.state;
    return (
       <React.Fragment>
        <p>You clicked {count} times</p>
        <button onClick={() => setState({count : count + 1})}>
          Click me
        </button>
      </React.Fragment>
    );
  }

}

接下来咱们看看用Hooks是如何实现的:编码

import React, { useState } from 'react';

export default () => {

  const [count, setCount] = useState(0);

  return (
    <React.Fragment>
      <p>You clicked { count } times</p>
      <button onClick={ () => setCount(count + 1) }>
        Click me
      </button>
    </React.Fragment>
  );
};

从代码结构上,减小了编码量。由原来的 class 组件变成 function 组件了。code

不一样的地方:生命周期

  • 新加入了 useState 方法
  • 经过 useState 钩子解构出了 statesetState 方法。
  • state 的默认值,直接经过 useState 传入
  • 更新 state 再也不使用 setState 方法。

若是有多个 state 怎么定义呢?

const [count, setCount] = useState(0);
const [name, setName] = useState(null);

在线示例
推荐阅读《React 手稿》

相关文章
相关标签/搜索