React生命周期总结

react生命周期流程

1.初始化,首次render

getDefaultProps 方法可以用来设置组件属性的默认值,在组件被建立时候就立即调用

getInitialState 方法用于定义初始状态

componentWillMount只在初始化时候被调用一次

render()

componentDidmount()在子组件也都加载完毕后执行,在RN中就是指组件初始化加载完毕,在react中DOM渲染完成

2.props发生改变时候更新

componentWillReceiveProps(nextProps)

componentWillReceiveProps方法可以比较this.props和nextProps来看是否发生了变化,然后可以进行setState等操作。
注意只要父组件此方法触发,那么子组件也会触发,也就是说父组件更新,子组件也会跟着更新。

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate 方法在接收了新的props或state后触发,可以通过返回true或false来控制后面的生命周期流程是否触发。

componentWillUpdate(nextProps, nextState)

componentWillUpdate在props或state改变或shouldComponentUpdate返回true后触发。不可在其中使用setState。
render()

重新渲染。

componentDidupdate(prevProps, prevState)

会等子组件也都更新完后才触发。

3.state发生改变时候更新

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate 方法在setState后state发生改变后触发,你可以通过返回true或false来控制后面的生命周期流程是否触发。

componentWillUpdate(nextProps, nextState)

componentWillUpdate在state改变或shouldComponentUpdate返回true后触发。不可在其中使用setState。

render()

重新渲染。

componentDidupdate(prevProps, prevState)

会等子组件也都更新完后才触发。

index作为key是一种反模式

1
2
3
{
this.state.data.map(el=><MyComponent key={Math.random()} />)
}

代码中MyComponent的key值是用Math.random随机生成的,虽然能够保持其唯一性,但是它的值是随机而不是稳定的,在数组动态改变时会导致数组元素中的每项都重新销毁然后重新创建,有一定的性能开销;另外可能导致一些意想不到的问题出现。所以:key的值要保持稳定且唯一,不能使用random来生成key的值。
所以,在不能使用random随机生成key时,我们可以像下面这样用一个全局的localCounter变量来添加稳定唯一的key值。

1
2
3
4
5
6
7
8
9
10
11
var localCounter = 1;
this.data.forEach(el=>{
el.id = localCounter++;
});
//向数组中动态添加元素时,
function createUser(user) {
return {
...user,
id: localCounter++
}
}

forEach和map和for方法的区别:

总结:
1、map速度比foreach快
2、map会返回一个新数组,不对原数组产生影响,foreach不会返回新数组,
3、map因为返回数组所以可以链式操作,foreach不能

为什么更推荐用.map(),而不是.forEach()?

第一:.map()要比.forEach()执行速度快。虽然我也说过执行速度不是我们需要考虑的主要因素,但是他们都比for()要好用,那肯定要选更优化的一个。
第二:.forEach()的返回值并不是array。如果你想用函数式编程写个链式表达式来装个逼,.map()将会是你不二的选择。

来看下面这个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var arr = [1, 2, 3];
console.log(
arr.map(function(i){
return i+i;
})
//链式风格
.sort()
);// [2,4,6]
console.log(
arr.forEach(function(i){
return i+i;
})
//接不起来,断了
.sort()
); // TypeError: Cannot read property 'sort' of undefined
最后,感谢大家耐心的阅读,排个序
.map() > .forEach() > for()

区别:map的回调函数中支持return返回值;return的是啥,就相当于返回一个新数组(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
不管是forEach还是map 都支持第二个参数值,第二个参数的意思是把匿名回调函数中的this进行修改。

es5的写法: bind可以改变this的指向

1
2
3
4
5
6
7
8
componentDidmount: function() {
alert('did');
window.setInterval(function(){
this.setState({
fontSize: '44px'
})
}, bind(this), 1000);
}