组件的状态state
定义组件的状态
interface IState {
auth: boolean
}
使用状态
import React, {Component} from "react";
interface IProps {
name: string
auth: boolean
}
interface IState {
auth: boolean
}
export default class App extends Component<IProps, IState> {
render() {
return (
<>
{this.props.name}
<br/>
{this.props.auth === true ? 'true' : 'false'}
<hr/>
</>
)
}
}
初始化状态
constructor(props: IProps, context: any) {
super(props, context);
this.state = {
auth: false
}
}
使用状态示例
只能在构造函数中赋值,其他地方不能直接修改 。this.state.auth=true,不允许的
import React, {Component} from "react";
interface IProps {
name: string
auth: boolean
}
interface IState {
auth: boolean
}
export default class App extends Component<IProps, IState> {
constructor(props: IProps, context: any) {
super(props, context);
this.state = {
auth: false
}
}
render() {
return (
<>
{this.props.name}
<br/>
{this.props.auth === true ? 'true' : 'false'}
<br/>
{this.state.auth === true ? 'true' : 'false'}
<hr/>
</>
)
}
}
更新状态
componentDidMount() {
setTimeout(() => {
this.setState({
auth: true
})
}, 2000)
}
State 是异步的,把多次状态更改合并成一个执行
下面示例是错误的
componentDidMount() {
for (var i = 0; i < 100; i++) {
this.setState({
auth: true,
num: this.state.num + i
})
console.log(i)
}
}
//99
正确结果
componentDidMount() {
for (let i = 0; i < 100; i++) {
this.setState((state) => ({
num: state.num + i
}))
console.log(i)
}
}
// 4950