reactjs -- 解决setState异步问题

JCh*_*hao 0 javascript reactjs

我读过这篇文章:React setState not Updating立即

并意识到 setState 是异步的,可能需要第二个 arg 作为处理新状态的函数。

现在我有一个复选框

class CheckBox extends Component {
    constructor() {
        super();
        this.state = {
            isChecked: false,
            checkedList: []
        };
        this.handleChecked = this.handleChecked.bind(this);
    }

    handleChecked () {
        this.setState({isChecked: !this.state.isChecked}, this.props.handler(this.props.txt));
    }

    render () {
        return (
            <div>
                <input type="checkbox" onChange={this.handleChecked} />
                {`   ${this.props.txt}`}
            </div>
            )
    }
}
Run Code Online (Sandbox Code Playgroud)

并且正在被另一个应用程序使用

class AppList extends Component {
    constructor() {
        super();
        this.state = {
            checked: [],
            apps: []
        };
        this.handleChecked = this.handleChecked.bind(this);
        this.handleDeleteKey = this.handleDeleteKey.bind(this);
    }
    handleChecked(client_id) {
        if (!this.state.checked.includes(client_id)) {
            let new_apps = this.state.apps;
            if (new_apps.includes(client_id)) {
                new_apps = new_apps.filter(m => {
                    return (m !== client_id);
                });
            } else {
                new_apps.push(client_id);
            }
            console.log('new apps', new_apps);
            this.setState({apps: new_apps});
            // this.setState({checked: [...checked_key, client_id]});
            console.log(this.state);
        }
    }
    render () {
        const apps = this.props.apps.map((app) =>
            <CheckBox key={app.client_id} txt={app.client_id} handler={this.handleChecked}/>
        );

        return (
            <div>
                <h4>Client Key List:</h4>
                {this.props.apps.length > 0 ? <ul>{apps}</ul> : <p>No Key</p>}
            </div> 
        );
    }


}
Run Code Online (Sandbox Code Playgroud)

所以每次复选框状态的变化,我更新this.state.appsAppList

当我 console.log new_apps,一切都相应地工作,但console.log(this.state)显示状态不会立即更新,这是预期的。我需要知道的是如何确保在需要执行进一步操作时更新状态(例如注册所有这些选定的字符串或其他操作)

Ric*_*sta 5

setState 使您可以在设置状态后进行回调函数,以便您可以获取真实状态

this.setState({stateYouWant}, () => console.log(this.state.stateYouWant))
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

this.setState({apps: new_apps}, () => console.log(this.state))
Run Code Online (Sandbox Code Playgroud)

  • 我所说的是同时执行,所以 console.log 有旧状态,如果你明白我的意思,它总是落后一个状态,这样做我们只在状态改变后记录(回调是通常是在某个操作完成后调用的函数,在这种情况下是 setState) (2认同)