我如何在我的React应用程序上使用localStorage?

时间:2019-10-17 15:25:09

标签: reactjs local-storage frontend

我正在从API提取数据,我想使用localStorage一小时,我需要在每小时之后获取数据。

  • 我的API如下:

    {
      "name": "My Name",
      "logo": "https://media.img.jpeg",
      "note": "14,5",
      "students": 3720,
      "url": "https://url.students/alain"
    }
    
  • 这是我的代码,https://codesandbox.io/s/busy-cloud-qzmef

3 个答案:

答案 0 :(得分:2)

您需要做的就是保存带有时间戳的必要数据。并检查日期是否已过期。

loadData = () => {
    // Check whether data exists in localStorage and has been
    // saved less than an hour ago
    const data = JSON.parse(localStorage.getItem('brand'));
    if (data && (new Date().getTime() - data.created <= 3600)) {
        this.setState({
            note: data.brand.note,
            logo: data.brand.logo,
            name: data.brand.name,
        });

        return;
    }

    // Otherwise perform request
    axios.get('https://myAPI.url').then(res => {
        const brand = res.data;

        // and save data in local storage with the current timestamp
        localStorage.setItem(
            'brand',
            JSON.stringify({
                created: new Date().getTime(),
                brand,
            }),
        );

        this.setState({
            note: brand.note,
            logo: brand.logo,
            name: brand.name,
        });
    });
};

答案 1 :(得分:0)

    // Save To localStorage
    const data = {
            "name": "My Name",
            "logo": "https://media.img.jpeg",
            "note": "14,5",
            "students": 3720,
            "url": "https://url.students/alain"
    }
    localStorage.setItem('key', JSON.stringify(data))


    // To Get data from localstorage 
    const data = JSON.parse(localStorage.getItem('key'));
    console.log(data);


    // To Remove Data
    localStorage.removeItem('key');
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

答案 2 :(得分:0)

建议不要将这些项目保存到localStorage中,而应将它们存储在redux存储中。 如果您不使用Redux:https://react-redux.js.org/introduction/quick-start