• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
wn0615
博客园    首页    新随笔    联系   管理    订阅  订阅

16生命周期(旧)render流程

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="test"></div>
</body>
</html>
<script type="text/babel">
class Count extends React.Component{
constructor(props) {
console.log('Count-constructor');
super(props);
//初始化状态
this.state={count:0}
}
//组件将要挂载的钩子
componentWillMount() {
console.log('Count---componentWillMount');
}
//组件挂载完毕后的钩子
componentDidMount() {
//一般做一些初始化的事例如:开启计时器,发送网络请求,订阅信息
console.log('Count---componentDidMount');
}
//组件将要卸载的钩子
componentWillUnmount() {
//一般在这个钩子中做一些收尾的工作,开入:关闭定时器,取消订阅消息
console.log('Count--componentWillUnmount');
}
//是否要进行数据更新(不写钩子默认为true,若写则必须写返回值)
shouldComponentUpdate() {
console.log('Count--shouldComponentUpdate');
//返回 Boolean值,true可以调用render
return true
}
//组件将要更新
componentWillUpdate() {
console.log('Count--componentWillUpdate');
}
//数据更新完毕
componentDidUpdate() {
console.log('Count--componentDidUpdate');

}
render(){
console.log('Count---render');
const {count} =this.state
return (
<div>
<h2>当前求和为:{count}</h2>
<button onClick={this.Add}>点我加一</button>
<button onClick={this.death}>卸载组件</button>
<button onClick={this.force}>不更改任何状态中的数据,强制更新</button>
</div>
)
}
Add=()=>{
//获取原始状态
const {count} =this.state
//更新状态
this.setState({count:count+1})
}
death=()=>{
ReactDOM.unmountComponentAtNode(document.querySelector("#test"))
}
//强制更新数据
force=()=>{
this.forceUpdate()
}

}
class A extends React.Component{
state={carName:'奔驰'}
changeCar=()=>{
this.setState({carName: '八手奥拓'})
}
render() {
return(
<div>
<div>A</div>
<button onClick={this.changeCar}>换车</button>
<B carName={this.state.carName} />
</div>

)
}
}
class B extends React.Component{
//组件 将要 接收 props的时候
componentWillReceiveProps(aaa) {
//第一次不走
console.log('B---componentWillReceiveProps');
console.log(aaa);

}
//是否需要进行组件数据更新
shouldComponentUpdate() {
return true
}
componentWillUpdate() {
console.log('B--componentWillUpdate');
}
//数据更新完毕
componentDidUpdate() {
console.log('B--componentDidUpdate');
}
render() {
console.log('B--render');
return(
<div>B,接受到的车是{this.props.carName}</div>
)
}
}
ReactDOM.render(<A/>,test)
</script>
posted @ 2022-07-06 10:16  大宁0615  阅读(23)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3