react 想要更新视图只能用 setState( ) 方法更改state
关于setState需要知道一下:
- setState是一个异步方法
- 修改state只能使用setState
关于setState的写法:
第一种:传递对象,直接修改
import React, { Component } from 'react'
class Hello extends Component {
constructor(props) {
super(props)
this.state = {
date: new Date()
}
}
tick() {
this.setState({
date: new Date()
})
}
}
第二种:传递方法,借助于 原有的state里的默认数据
import React, { Component } from 'react'
class Hello extends Component {
constructor(props) {
super(props)
this.state = {
date: new Date()
}
}
handleClick = () => { // 属性初始化器语法绑定this,(类的方法默认是不会绑定 this 的)
this.setState(state => ({
isToggleOn: !state.isToggleOn
}))
}
}