一、state是什么?
state 是 class组件的内置对象,用于class组件内部数据更新,譬如可以封装一个Clock组件,每秒更新一次时间。
二、怎么使用?
1、使用state封装的Clock组件
新建index.html文件,复制下面代码到index.html文件中,保存后用浏览器打开,就可以看到效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<!-- 第一步:加载开发版本的React -->
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<!-- 部署时,请用下面链接替代上面 -->
<!-- <script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script> -->
<!-- 第二步:加载开发版本的babel -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Clock extends React.Component {
constructor(props) {
super(props);
// 1、初始化 state
this.state = { date: new Date() };
}
// 组件被渲染到 DOM 中后运行:组件挂载
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
// 组件卸载
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
// 2、更新 state 数据
this.setState({
date: new Date()
});
}
// 3、获取state的值并显示
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
</script>
</body>
</html>
2、state三个特性
// 1.错误:只能调用 setState 方法修改 state 对象
this.state.comment = 'Hello';
// 2.正确 :只能调用 setState 方法修改 state 对象
this.setState({ comment: 'Hello' });
// 3.正确:只能在构造函数中,初始化 this.state