# 类组件响应式视图实现与原理
# 类组件响应式视图
通过state设置响应式视图,他是组件内私有的,受控于当前组件。通过state的变化,就可以影响到视图的变化。
class Welcome extends React.Component {
state = {
msg: 'hello',
count: 0
}
render(){
return (
<div>
{this.state.msg}, {this.state.count}
</div>
);
}
}
let element = (
<Welcome />
);
这样就可以在页面中渲染msg
和count
这两个字段了,那么怎么才能让state修改后视图跟着发生变化呢,首先不能像Vue那样直接对数据进行修改,在React中是不行的。
React类组件中式通过一个具体的方法setState()
进行state数据的更新,从而触发render()
方法的重渲染操作。
class Welcome extends React.Component {
state = {
msg: 'hello',
count: 0
}
handleClick = () => {
//this.state.msg = 'hi' //永远不要这样去操作
this.setState({
msg: 'hi'
});
}
render(){
console.log('render');
return (
<div>
<button onClick={this.handleClick}>点击</button>
{this.state.msg}, {this.state.count}
</div>
);
}
}
let element = (
<Welcome />
);
state改变视图的原理就是内部会重新调用render()
方法,俗称re-render
操作。
这里还有注意一点,setState()并不会影响其他state值,内部会完成合并的处理。