常见功能实现
# 监听数据变化
fn component 使用
useEffect(() => {
console.log('counter发生了变化,最新值:', counter);
}, [counter]);
1
2
3
2
3
class component 使用 get()
class Test extends Component {
state = { counter: 0 };
get newCounter(): number {
const { counter } = this.state;
console.log(`counter changed, new value: ${counter}`);
return counter;
}
handleClick = (): void => {
this.setState({ counter: this.state.counter + 1 });
}
render(): JSX.Element {
return (<div>
<p>{this.newCounter}</p>
<Button onClick={this.handleClick.bind(this)}>click + 1</Button>
</div>);
}
}
export default Test;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
生命周期hook
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
1
2
2
上次更新: 2022/08/14, 18:25:44