实例:react
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> ) } }
Timer 在线实例git
写在constructor
函数中,是一个Object
对象。通常状况下须要指定默认值,预防抛undefined
.github
在组件中经过访问组件对象属性的方式。直接获取:this.state.time
.
咱们一般会先获取state
数据,再渲然到页面,例如:异步
render() { const {time} = this.state; return ( <div>{time}</div> ); }
先看一段代码:函数
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> ); } }
数据单和向性this
input
与div
中直接显示name
的内容,可是,在input
中直接输入内容,div
的显示不会改变。code
把这种组件也称为非受控性组件。
setStatecomponent
经过React提供了setState
方法,来实现state
的修改。对象
咱们只要将上述的非受控性组件修改成受控性组件便可,以下:jsx
<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 //this.setState({...this.state, addree: 'xi an'}); //可是这种方式在对象修改的时候很是有用。 console.log(this.state) //{name: 'xiaoshouyi', address: 'xi an'}
相似与Object.assgin()
。
回调
this.setState({name: 'changed'}, () => { console.log(this.state.name); // changed });
推荐阅读《React 手稿》