无法在setState中存储数据做出反应

two*_*oam 1 javascript reactjs

首先,我检查是否支持Localstorage,如果是,我检查localstorage中是否有项目查询.如果有项目,则应更新为查询状态.在setState之前,我有一个警报,它会提醒项目.但是在setState之后我再次提醒但它什么都没显示?有人知道为什么吗?即使我this.setState({query: localStorage.getItem("query")})this.setState({query: 'test'})它取代它也不会在警报中显示测试?

getLocalStorage = () => {
    if (typeof(Storage) !== "undefined") {

        if (localStorage.getItem("query") !== null) {
            //Alerts 'a string'
            alert(localStorage.getItem("query"));

            this.setState({
                query: localStorage.getItem("query")
            });

            //Alerts nothing?
            alert(this.state.query);
            this.search();
        }
        else{
            this.getLocation();
        }
    }
    else {
        this.getLocation();
    }
};
Run Code Online (Sandbox Code Playgroud)

Viv*_*shi 5

setState不会显示直接更改,需要时间:

setState()并不总是立即更新组件.它可以批量推迟更新或推迟更新.这使得在调用setState()之后立即读取this.state是一个潜在的陷阱.相反,使用componentDidUpdate或setState回调(setState(更新程序,回调)),其中任何一个都保证在应用更新后触发.如果需要根据以前的状态设置状态,请阅读下面的updater参数.

如果您想要在设置之后的状态值,您必须像这样使用它:

this.setState({
    query: localStorage.getItem("query")
},() => {
    alert(this.state.query);
});
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请阅读setState