state 和 生命周期

本文介绍了如何将React的函数组件转换为类组件,并添加局部状态和生命周期方法。首先,展示了如何创建Clock组件,然后演示了如何在类组件中设置state并实现组件的挂载和卸载时的定时器管理。强调了正确使用state的原则,如避免直接修改state,理解state更新的异步性质,以及state更新的合并。最后,讨论了React应用中的数据流向和单向数据流原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

封装Clock组件

通过学习clock组件,了解生命周期以及state

function Clock(){
	return (
  	<div>
    	<h1> now time is </h1>
    	<h2> {new Date().toLocaleTimeString()}</h2>
    </div>
  )
}

function tick(){
  ReactDOM.render(
  	<Clock date={new Datep()} />,
		document.getElementById('root')
  );
}
setInterval(tick,1000)
将函数组件装换成Class组件
class Clock extends React.Component{ // 创建一个Clock的类,并且继承React.Component。
  render(){  // 添加一个render()方法;
    return( // 使用this.props 替换 props
    	<div>
      	<h1> now time is </h1>
    		<h2> {this.props.date.toLocaleTimeString()}</h2>
      </div>
    )
  }
}
向class组件中添加局部的state
class Clock extends React.Component{ 
  constructor(props){ // 添加一个构造函数,为this.state 赋值
    super(props); // 将props传递到父类,调用父类构造函数。
    this.state = {date:new Date()}
  }
  render(){ // 将this.props.date 替换成 this.state.date
    return(
    	<div>
      	<h1> now time is </h1>
    		<h2> {this.state.date.toLocaleTimeString()}</h2>
      </div>
    );
  }
}
ReactDOM.render(
	<Clock />, // 移除date属性。
  document.getElementById('root')
)
将生命周期添加到Class中

当组件被销毁时释放所占有的资源是非常有必要的。

生命周期中便有挂载卸载的概念。

class Clock extends React.Component{ 
  constructor(props){
    super(props); 
    this.state = {date:new Date()}
  }
  componentDidMount(){ // 挂载时执行
    // 组件渲染完成后,设置定时器
    this.timer = setInterval(() => this.tick(),1000);
  }
  componentWillUnmount(){ // 卸载时执行
 		// 组件在销毁前执行
    clearInterval(this.timer)
  }
  render(){ 
    return(
    	<div>
      	<h1> now time is </h1>
    		<h2> {this.state.date.toLocaleTimeString()}</h2>
      </div>
    );
  }
}
ReactDOM.render(
	<Clock />, 
  document.getElementById('root')
)
正确的使用 State
  1. 不要直接修改state
this.state.val = 'good'; // 此代码不会重新渲染组件;
// 应使用 setState()
this.setState({val:'good'}); // 构造函数时唯一可以给this.state赋值的地方。
  1. state的更新可能是异步

因为 this.propsthis.state 可能会异步更新,所以你不要依赖他们的值来更新下一个状态

this.setState({
  val: this.state.val + this.props.val, // val可能无法更新。
});
// 应使用 函数 代替 对象
this.setState((state,props)=>({
  return{
  	val:state.val + props.val
	}
}));
  1. state 的更新会被合并

调用setState() 的时候,React会把提供的对象合并到当前的state中。

数据是向下流动的

这通常会被叫做“自上而下”或是“单向”的数据流。任何的 state 总是所属于特定的组件,而且从该 state 派生的任何数据或 UI 只能影响树中“低于”它们的组件。


点赞 评论 收藏 ~~ 今天的React学习到这结束了 ~~ 点赞 评论 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shaoin_2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值