封装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
- 不要直接修改state
this.state.val = 'good'; // 此代码不会重新渲染组件;
// 应使用 setState()
this.setState({val:'good'}); // 构造函数时唯一可以给this.state赋值的地方。
- state的更新可能是异步
因为 this.props
和 this.state
可能会异步更新,所以你不要依赖他们的值来更新下一个状态
this.setState({
val: this.state.val + this.props.val, // val可能无法更新。
});
// 应使用 函数 代替 对象
this.setState((state,props)=>({
return{
val:state.val + props.val
}
}));
- state 的更新会被合并
调用setState()
的时候,React会把提供的对象合并到当前的state中。
数据是向下流动的
这通常会被叫做“自上而下”或是“单向”的数据流。任何的 state 总是所属于特定的组件,而且从该 state 派生的任何数据或 UI 只能影响树中“低于”它们的组件。
点赞 评论 收藏 ~~ 今天的React学习到这结束了 ~~ 点赞 评论 收藏