Hooks是React v16.7.0-alpha中加入的新特性。它可以让你在class以外使用state和其他React特性
1.state hook的使用
useState
是一个Hook,它允许您将React状态添加到功能组件(常说的无状态组件)
使用场景:如果你编写一个函数组件并意识到你需要为它添加一些状态,那么之前你必须将它转换为一个类。现在,您可以在现有功能组件中使用useState
例如:
//我们useState从React 导入Hook。它允许我们将本地状态保存在功能组件中
import { useState } from 'react';
function Example() {
//count 相当于this.state.count useState(0)相当于this.setState({conut:0})
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
等效于
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>
);
}
}
使用state的属性
<p>这是之前的state使用方式 {this.state.count}</p>
<p>在React v16.7.0-alpha可以这么用 {count} </p>
修改state的值
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
这是之前的修改方式
</button>
<button onClick={() => setCount(count + 1)}>
React v16.7.0-alpha可以这么用
</button>
2.Effect Hook的使用
你可以把 useEffect
Hooks 视作 componentDidMount
、componentDidUpdate
和 componentWillUnmount
的结合
我们在 React 更新 DOM 之后立刻更新 document title
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
等效于
Js中文网 – 前端进阶资源教程 www.javascriptC.com,typescript 中文手册
专注分享前端知识,你想要的,在这里都能找到
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
//默认情况下 它会在第一次 render 和之后的每次 update 后运行
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
作者:藤蔓绕竹
链接:https://juejin.im/post/5c46c6706fb9a049d975888a
看完两件小事
如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:
- 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
- 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程
本文著作权归作者所有,如若转载,请注明出处
转载请注明:文章转载自「 Js中文网 · 前端进阶资源教程 」https://www.javascriptc.com