React Hooks
React在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 [email protected] [email protected]
//或者
yarn add [email protected] [email protected]
<h1>State Hooks</h1>
<p>首先看一个React既有的版本基于 <code>class</code> 的组件.</p>
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>
);
}
}
<p>接下来我们看看用Hooks是如何实现的:</p>
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>
);
};
<p>从代码结构上,减少了编码量。由原来的 <code>class</code> 组件变成 <code>function</code> 组件了。</p>
<p>不同的地方:</p>
<ul>
<li>新加入了 <code>useState</code> 方法</li>
<li>通过 <code>useState</code> 钩子解构出了 <code>state</code> 与 <code>setState</code> 方法。</li>
<li>
<code>state</code> 的默认值,直接通过 <code>useState</code> 传入</li>
<li>更新 <code>state</code> 不再使用 <code>setState</code> 方法。</li>
</ul>
<p>如果有多个 <code>state</code> 怎么定义呢?</p>
const [count, setCount] = useState(0);
const [name, setName] = useState(null);
```
在线示例
推荐阅读《React 手稿》
来源:https://segmentfault.com/a/1190000017261209