一、react基础
- react类组件负责逻辑控制,比如修改数据 ==> vdom
- ReactDOM负责渲染,vdom ==> dom
- babel-loader可以转化 jsx ==> vdom
==> React.createElement('h1','react真帅')react真帅
1、setState
(1)基础
this.state={
count:0
}
// 改变state
this.setState({
count: this.state.count + 1
})
this.setState({
count: this.state.count + 1
})
this.setState({
count: this.state.count + 1
})
console.log(this.state.count)
解析:
- 三次setState, 只以最后一次为准
- 打印this.state.count仍然为0,因为setState是异步
(2)setState用法
this.state={
count:0
}
// 改变state
this.setState((state: any, props: any) => {
console.log('setState1 内部: ',state.count)
return { count: state.count + 1 }
}, () => {
console.log('setState1 回调: ',this.state.count)
})
this.setState((state: any, props: any) => {
console.log('setState2 内部: ',state.count)
return { count: state.count + 1 }
}, () => {
console.log('setState2 回调: ',this.state.count)
})
this.setState((state: any, props: any) => {
console.log('setState3 内部: ',state.count)
return { count: state.count + 1 }
}, () => {
console.log('setState3 回调: ',this.state.count)
})
setTimeout(() => {
console.log('setTimout: ',this.state.count)
})
console.log('正常:', this.state.count)
(3)原生dom事件中setState
this.state={
count:3
}
// dom改变state
document.body.addEventListener('click',()=>{
this.setState((state: any, props: any) => {
console.log('setState 内部: ', state.count)
return { count: state.count + 1 }
}, () => {
console.log('setState 回调: ', this.state.count)
});
console.log('正常:', this.state.count)
})
执行结果:
只针对原生dom事件,如果是react虚拟dom, setState仍然是异步
2、生命周期
(1)16.0之前的生命周期
(2)16.3的生命周期
(3)16.4的生命周期
(4)测试代码
/**
* 挂载、卸载过程
*/
// componentWillMount() {
// // 组件将要挂载, 可以访问状态和属性, api调用
// console.log('componentWillMount')
// }
componentDidMount() {
// 组件已经挂载, 可以进行状态更新操作
console.log('componentDidMount');
}
componentWillUnmount() {
// 组件将卸载
console.log('componentWillUnmount');
}
/**
* 更新过程
*/
// componentWillReceiveProps(nextProps: any) {
// // 父组件传递的属性有变化, 将要接收属性传递
// console.log('componentWillReceiveProps', nextProps)
// }
// shouldComponentUpdate(nextProps: any, nextState: any) {
// // 组件是否需要更新,属性和state都会走到这里,需要返回true/false, 性能优化点
// console.log('shouldComponentUpdate', nextProps, nextState)
// return nextProps.age !== this.props.age || nextState.count !== this.state.count
// }
// componentWillUpdate(nextProps: any, nextState: any) {
// // 组件将要更新, 可做更新统计
// console.log('componentWillUpdate', nextProps, nextState)
// }
componentDidUpdate(prevProps: any, prevState: any) {
// 组件已经更新
console.log('componentDidUpdate', prevProps, prevState)
}
/**
* 新增的生命周期,代替
* componentWillMount
* componentWillReceiveProps
* componentWillUpdate
* shouldComponentUpdate
*/
static getDerivedStateFromProps(nextProps: any, nextState: any) {
console.log('getDerivedStateFromProps', nextProps, nextState)
return true
}
// getSnapshotBeforeUpdate(prevProps: any, prevState: any) {
// console.log('getDerivedStateFromProps', prevProps, prevState)
// }