實例: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 手稿》