React

组件内部的数据

状态

代码示例:

// src/test/Test01.jsx

import React, {Component} from 'react';

export default class Test01 extends Component {
    state = {  // 关键字
        myShow: true
    }

    render() {
        return (
            <div>
                <button onClick={() => {
                    this.setState({  // setState:改变状态
                        myShow: !this.state.myShow  // 取反
                    })
                    if (this.state.myShow) {
                        console.log('收藏的逻辑')
                    } else {
                        console.log('取消收藏的逻辑')
                    }
                }}>{this.state.myShow ? '收藏' : '取消收藏'}</button>
            </div>
        );
    }
}
// src/test/Test01.jsx

import React, {Component} from 'react';

export default class Test01 extends Component {
    constructor() {
        super()  // 继承父类的属性
        this.state = {
            myShow: true,
            myName: true
        }
    }

    render() {
        return (
            <div>
                <h1>欢迎:{this.state.myName ? 'Foo' : 'Bar'}</h1>
                <button onClick={() => {
                    this.setState({
                        myShow: !this.state.myShow,
                        myName: !this.state.myName
                    })
                    if (this.state.myShow) {
                        console.log('收藏的逻辑')
                    } else {
                        console.log('取消收藏的逻辑')
                    }
                }}>{this.state.myShow ? '收藏' : '取消收藏'}</button>
            </div>
        );
    }
}
// src/test/Test03.jsx

import React, {Component} from 'react';

export default class Test03 extends Component {
    state = {
        num: 0
    }

    click01() {  // 同步环境(setState的第二个实参:当状态更新完毕之后会立即调用回调函数)
        this.setState({
            num: this.state.num + 1
        }, () => {
            console.log(this.state.num)
        })
        this.setState({
            num: this.state.num + 1
        }, () => {
            console.log(this.state.num)
        })
        this.setState({
            num: this.state.num + 1
        }, () => {
            console.log(this.state.num)
        })
    }

    async click02() {  // 异步环境(setTimeout与setInterval在React18时setState都是异步执行)
        this.setState({
            num: this.state.num + 1
        })
        await console.log(this.state.num)
        this.setState({
            num: this.state.num + 1
        })
        await console.log(this.state.num)
        this.setState({
            num: this.state.num + 1
        })
        await console.log(this.state.num)
    }

    render() {
        return (
            <div>
                <button onClick={() => {
                    this.click01()
                }}>同步环境
                </button>
                <button onClick={() => {
                    this.click02()
                }}>异步环境
                </button>
            </div>
        );
    }
}