Component state
实例:
import React, { PureComponent } from 'react';
export default class extends PureComponent {
constructor(props) {
super(props);
this.state = { time: '' };
}
componentDidMount() {
setInterval(() => {
const now = new Date();
let { time } = this.state;
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconde = now.getSeconds();
time = ${0000${year}.slice(-4)}-${00${month}.slice(-2)}-${00${day}.slice(-2)} ${00${hours}.slice(-2)}:${00${minutes}.slice(-2)}:${00${seconde}.slice(-2)}
this.setState({ time });
}, 1000);
}
render() {
return (
<div>{this.state.time}</div>
)
}
}
定义
写在constructor
函数中,是一个Object
对象。一般情况下需要指定默认值,预防抛undefined
.
使用
在组件中通过访问组件对象属性的方式。直接获取:this.state.time
.
我们通常会先获取state
数据,再渲然到页面,例如:
render() {
const {time} = this.state;
return (
<div>{time}</div>
);
}
setState
先看一段代码:
import React, {PureComponent} from 'react';
export default class extends PureComponent {
constructor(props) {
super(props);
this.state = {name: 'world'};
}
render() {
const {name} = this.state;
return (
<div>
<input defaultValue={name} name="name" />
<div>Holle, {name}!</div>
</div>
);
}
}
- 数据单和向性
input
与div
中直接显示name
的内容,但是,在input
中直接输入内容,div
的显示不会改变。
把这种组件也称为非受控性组件。 - setState通过React提供了
setState
方法,来实现state
的修改。我们只要将上述的非受控性组件修改为受控性组件即可,如下: <input value={name} onChange={e => this.setState({name: e.target.value})} />使用setState
方法需要注意以下几点:
- 异步
onChange () { this.setState({name: 'hasChanged'}) console.log(this.state.name === 'hasChanged'); //false } - 合并
this.state = {name: 'xiaoshouyi', address: 'beijing'};
this.setState({address: 'xi an'});
//not
/