didmount&&willunmount

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export default class A extends React.Component {

constructor(props) {
super(props);
}
scroll1(){}

componentDidMount() {
window.addEventListener('scroll', this.srcoll1.bind(this));
}

componentWillUnmount(){
window.removeEventListener('scroll', this.srcoll1);

}

render() {
};

}

when using event handler in render(), need to bind this to the function
inside constructor, it will be global. otherwise, everytime inside render() we need to bind this when we use the method everytime, it will be awaste of time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export default class A extends React.Component {

constructor(props) {
super(props);
this.scroll1 = this.scroll1.bind(this)
}
scroll1(){}

componentDidMount() {
window.addEventListener('scroll', this.scroll1);
}

componentWillUnmount(){
window.removeEventListener('scroll', this.scroll1);

}

render() {
};

}

bind方法,顾名思义,就是绑定的意思,到底是怎么绑定然后怎么用呢,下面就来说说我对这个方法的理解。

bind的使用和call,apply的区别:都是将方法的主人绑定,this指向全局object。
bind will not be executed imediately while call, aply will execute right away.
为什么要创建绑定函数,就是当我们调用某些函数的时候是要在特定环境下才能调用到,所以我们就要把函数放在特定环境下,就是使用bind把函数绑定到特定的所需的环境下。