首页 > 解决方案 > React - 在继续之前使用 axios 数据设置本地存储

问题描述

为我的反应应用程序设置正确的初始化时遇到了一个小挑战。在本地存储中有一些设置,我想用来自 axios get 请求的数据填充它们,然后再发生应用程序中的其他任何事情(例如初始化其余的构造函数行)。当前发生的情况是,当该行执行时,代码继续并读取尚未更新的“旧”本地存储:

APP.JS
...
this.readSettingsDB(false);

this.state = {
  chartTimeAggregationType: JSON.parse(localStorage.getItem('timeAggregationType')) // <-- This value is still old
  dataLoading: true,
  ...



readSettingsDB(refreshPage) {
    data = axios.get('/someurl').then(response => {
    localStorage.setItem('timeAggregationType': reponse.time)
    });
}

标签: reactjsaxios

解决方案


Where are you using refreshPage? Here is how I would handle your issue.

readSettingsDB = async (refreshPage) => {                  // arrow function make async
    const data = await fetch('/someurl');     // use fetch
    const response = await data.json();  
    localStorage.setItem('timeAggregationType': reponse) // set storage
    });
}

If you want to setState first, setState comes with a callback.

readSettingsDB = async (refreshPage) => {                  // arrow function make async
    const data = await fetch('/someurl');     // use fetch
    const response = await data.json();  
this.setState({
timeAggregationType: reponse 
}, () => {
    localStorage.setItem('timeAggregationType': this.state.timeAggregationType) // set storage
    });
})

}

推荐阅读