首页 > 解决方案 > 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 中新检索到的数据。


标签: javascriptreactjs

解决方案


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 保留数据。


推荐阅读