React Hooks

什么是React Hooks
React Hooks 要解决的是状态共享,是继render-props() 和higher-order components(高阶组件)之后的第三种状态共享方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function App(){
const [open,setOpen] = useState(false);
return(
<>
<Button type="primary" onClick = {() => setOption(true)}>
Open Modal
</Button>
</>
<Modal
visible={open}
onOk={() =>setOpen(false)}
onCancel={() => setOpen(false)}
/>
)
}

React Hooks 就想一个内置的打平 renderProps 库,我们可以创建一个值,与修改这个值得方法。看上去像function形势的setState,其实这等价于依赖注入,与使用setState相比,这个组件是没有状态的。

React Hooks 的特点
React Hooks 带来的好处不仅是“更FP,更新粒度更细,代码更清晰”
1.多个状态不会产生嵌套,写法是平铺的(renderProps可以通过compose解决,不但使用略为繁琐,而且因为强制封装一个新对象而增加了实体数量)。
2.Hooks 可以引用其他Hooks
3.更容易将组件的UI与状态分离。

利用useEffect代替一些生命周期

1
2
3
4
5
6
useEffect(() => {
const subscription = props.source.subscribe();
return() =>{
subscription.unsubscribe();
}
})

useEffect 的代码既会在初始化的时候执行,也会在后续每次rerender时执行,而返回值解析结构时执行。这个更多带来的便利,对比G2图表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
this.chart = new G2.Chart({
container: document.getElementById("chart"),
forceFit:true,
height:300
});
this.freshChart(this.props)

componentWillReceiveProps(nextProps:Props){
this.freshChart(nextProps);
}
componentWillUnmount(){
this.chart.destroy();
}
freshChart(props:Props){
this.Chart.render();
}
render(){
return <div ref={ref => (this.rootDomRef = ref)} />;
}

[React Hooks 入门教程][1]
[1]:http://www.ruanyifeng.com/blog/2019/09/react-hooks.html