React HooksReact在16.7.0-alpha.0版本中提到了Hooks的概念,目前还是Proposal阶段。官方也陈述,接下来的90%的工作会投入到React Hooks中。从目前官方的文档可以看出,Hooks从以下四个方面来提高React的编码。state生命周期content自定义方法Hooks的主要用途是替代之前版本的 class 组件。说明:到目前为止,React在已发布的release版本中有该功能,想体验该功能,必须安装16.7.0-alpha.0。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.0State Hooks首先看一个React既有的版本基于 class 的组件.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 组件了。不同的地方:新加入了 useState 方法通过 useState 钩子解构出了 state 与 setState 方法。state 的默认值,直接通过 useState 传入更新 state 不再使用 setState 方法。如果有多个 state 怎么定义呢?const [count, setCount] = useState(0);const [name, setName] = useState(null);在线示例推荐阅读《React 手稿》