其实在前面文章写过几次 Hook ,其实动作也就三个。
import React, { useState } from 'react';
function Example() {
// 宣告
const [count, setCount] = useState(0);
return (
<div>
//读取
<p>You clicked {count} times</p>
//更新
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
什麽是解构赋值?
解构赋值 (Destructuring assignment) 语法是一种 JavaScript 运算式,可以把阵列或物件中的资料解开撷取成为独立变数。 - MDN
宣告 state 的写法,console.log 回传值如下图
拆解出来就是下面的对照
const [state, setState] = React.useState({
count: 0,
});
//对照
const [state, setState] = [{count: 0}, ƒ ()]
Hook 看起来稍微简洁,也不需要写 constructor 或 super 的结构,以及使用 this 关键字。
Class 范例
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}}
Hook 范例
import React, { useState } from 'react';
function Example () {
[count, setCount] = React.useState(0)
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
要注意的是,在 Class 里使用 setState 的时候,物件的值会是 merge 在一起的,只更新更新的部分。
但使用 Hook 去更新物件资料,会是完全覆盖,所以需要连同原来的值一起传入。以下例子跟反例 anti pattern 。
使用物件的例子
function Example () {
[fruit, setFruit] = React.useState({
name: 'apple',
count: 0
})
return (
<div>
<p>{fruit.name}</p>
<p>You clicked {fruit.count} times</p>
<button onClick={() => setFruit({...fruit, count: fruit.count + 1})}>
Click me
</button>
</div>
);
}
//略
使用物件的反例,原本的值就会消失了。
function Example () {
//略
return (
<div>
<p>{fruit.name}</p>
<p>You clicked {fruit.count} times</p>
<button onClick={() => setFruit({count: fruit.count + 1})}>
Click me
</button>
</div>
);
}
//略
在还没有 Hook 的时候,可能会再不需要用到 state 的时候选择使用 function component,因为不需要写 Class 结构,这样没有 state 的 componennt 也叫做 Stateless component (以下举例),但若遇到之後要使用 state 或生命周期,就必须重新改写成 Class。
const CoverImage = (props) => {
return (
<picture>
<source srcset={props.source} >
<img src={props.default} alt={props.alt} />
</picture>
);
}
以上今天。
参考资料:
https://zh-hant.reactjs.org/docs/hooks-state.html
解构赋值
<<: Day 17 | Flutter的常用 widgets - Container、Row、Column
>>: 架站:Wordpress apps + DDNS+SSL+Port Forward
树耳朵 oh les feuilles 地点:台南市白河区94-7号 时间:五六日 13:00~17...
模拟 Skeleton Loader https://www.youtube.com/watch?v...
本系列文章同步发布於笔者网站 前言 大家好,我是 Gene,如果有参与过 Cloud Native ...
今天接续着我们昨天models.py的下半段,说明Field用法的部分,这对於在写model时候是另...
今日题目:290. Word Pattern(Easy) Given a pattern and a...