react-native的组件生命周期总结:
生命周期 | 调用次数 | 能否使用setState() |
---|---|---|
getDefaultProps | 1(全局调用一次) | 否 |
getInitialState | 1 | 否 |
componentWillMount | 1 | 是 |
render | >=1 | 否 |
componentDidMount | 1 | 是 |
componentWillReceiveProps | >=0 | 是 |
shouldComponentUpdate | >=0 | 否 |
componentWillUpdate | >=0 | 否 |
componentDidUpdate | >=0 | 否 |
componentWillUnmount | 1 | 否 |
注意:当调用this.setState时就会调用组件的render方法,但React框架会根据dom节点状态确定是否需要重新渲染。
this.setState
this.setState用法
this.setState(arg1,arg2),arg1可以是对象也可以是函数(必需),arg2是一个回调函数,在此函数中可以获取被setState更改后的state值,arg2可为空。
当arg1是对象时的写法:
this.setState({
key : val
},()=>{
console.log(this.state.key);
})
当arg1是函数时的写法:
//第一种写法(在更改state值之前执行一些操作)
this.setState(
(prevState,props)=>{
console.log(prevState);
return { key : prevState.key+props.val };
},()=>{
console.log(this.state.key);
}
);
//第二种写法
this.setState(
(prevState,props)=>({
key : prevState.key+props.val
}),()=>{
console.log(this.state.key);
}
);
this.setState的使用场景
当通过this.state.key = val直接修改state值时,虽然可以更改state值,但是不会触发re-render对组件进行重新渲染,使用this.setState()更改state数据值,会触发re-ren