javascript - React:刷新时如何持久化数据?渲染时从 API 检索数据
问题描述
以下是我在主 App JS 文件中的组件:
class App extends React.Component {
state = {
myValue: 'some value'
}
componentDidMount() {
// retrieve the data from an API and save them into state
myApi.getData().then((myData) => {
this.setState(myData);
});
}
render() {
return (
// render the website corresponding to the retrieved data (state)
)
}
}
渲染后,state
(数据)被改变。刷新网站时,状态设置为从 API 中新检索到的数据。
- 刷新后如何保留更改的数据?(刷新时不获取新数据?)
解决方案
class App extends React.Component {
state = {
myData: 'some value'
}
componentDidMount() {
let myDataFromSessionStorage = JSON.parse(sessionStorage.getItem("myData"))
if (!myDataFromSessionStorage) {
// retrieve the data from an API and save them into state
myApi.getData().then((myData) => {
this.setState({
myData,
}, () => {
//Callback which will be executed once the state has been set
sessionStorage.setItem("myData", JSON.stringify(myData))
});
});
} else {
this.setState({
myData: myDataFromSessionStorage,
})
}
}
render() {
return (
// render the website corresponding to the retrieved data (state)
)
}
}
即使重新打开浏览器,也可以使用 localstorage 保留数据。
推荐阅读
- c# - HttpWebRequest 异常无法解析远程名称:'http'
- javascript - 如果选中复选框,如何显示 div 元素?
- sql - 在 mysql 计数查询方面需要帮助
- c++ - 使用通用函数调用打印结构的所有嵌套成员变量
- node.js - 如何将winston@3.0.0 用于winston-azure-blob-transport?
- javascript - 为什么数据表在 LIVE 服务器中加载数据较慢?
- g++ - 为什么 VLA 的 sizeof 的 memset 在不同的 C++ 版本上的工作方式不同?
- android - Dagger 2:子组件中存在匹配键
- sql-server - 如何在 SQL Server Management Studio 中使用不同的 where 子句语句创建视图?
- c# - 在 .Net Core 中检查动态模型的空属性