React
基本用法以及
class Count extends React.Component {
// 构造器
constructor(props) {
super(props)
this.state = { num: 0 }
}
// 初始化状态
state = { num: 0 }
render() {
return (
<div>
<h2>当前求和为:{this.state.num}</h2>
<button onClick={this.add}>点我+1</button>
<button onClick={this.death}>卸载组件</button>
<button onClick={this.force}>不更改状态中任何数据,强制更新</button>
</div>
)
}
add = () => {
let { num } = this.state
num++;
this.setState({ num });
}
death = () => {
// 卸载组件
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
force = () => {
this.forceUpdate()
}
// 组件将要挂载的钩子
componentWillMount() {
console.log('Count——componentWillMount: ');
}
// 组件挂载完毕的钩子
componentDidMount() {
console.log('Count——componentDidMount: ');
}
// 组件将要卸载
componentWillUnmount() {
console.log('Count——componentWillUnmount ')
}
// 控制组件更新的 “ 阀门 ” 必须有返回值,不写这个钩子函数默认返回为true,返回false则不进行更新
shouldComponentUpdate() {
console.log('Count——shouldComponentUpdate')
return true
}
// 组件将要更新的钩子
componentWillUpdate() {
console.log('Count——componentWillUpdate ')
}
// 组件将要更新完毕的钩子
componentDidUpdate() {
console.log('Count——componentDidUpdate ')
}
}
ReactDOM.render(<Count />, document.getElementById('test'))
componentWillReceiveProps的用法
class A extends React.Component {
state = { carName: '法拉利' }
render() {
return (
<div>
<h2>我是A组件</h2>
<button onClick={this.changeCar}>换车</button>
<B carName={this.state.carName}></B>
</div>
)
}
changeCar = () => {
this.setState({ carName: '保时捷' });
}
}
class B extends React.Component {
render() {
return (
<div>
<h2>我是B组件,接收到的车是:{this.props.carName}</h2>
</div>
)
}
componentWillReceiveProps() {
console.log('B-----componentWillReciveProps')
}
}
ReactDOM.render(<A />, document.getElementById('test'))
注意:
1、componentWillReceiveProps()首次加载并不会被调用,只有在数据更新时会被调用;
2、componentWillMount()、componentWillUpdate()、componentWillReceiveProps()在17版本以后可以会有一个名称更改的变化。
3、更改以后的名称为UNSAFE_componentWillMount()、UNSAFE_componentWillUpdate()、UNSAFE_componentWillReceiveProps()。详情请查看官网连接
总结:
1.初始化阶段:由ReactDOM.render()触发---初次渲染
1.constructor()
2.componentWillMount()
3.render()
4.componentDidMount() ======> 常用,一般做一些数据的初始化。 比如:开启定时器,发送请求,订阅消息等等
2.更新阶段:由组件内部this.setState()或父组件render触发
1.shouldComponentUpdate()
2.componentWillUpdate()
3.render() =====> 必须使用
4.componentDidUpdate()
3.卸载组件:由 ReactDOM.unmountComponentAtNod()触发
1.componentWillUnmount() =====> 常用,一般做一些收尾的工作。 比如:关闭定时器,取消订阅消息