简体   繁体   English

API刷新页面丢失数据?

[英]Refreshing page lost data of API?

hi everyone i am getting data from api in react and also storing token in my local storage but when i refresh the page my data of API lost but my token remain save in local storage.大家好,我在反应中从 api 获取数据并将令牌存储在我的本地存储中,但是当我刷新页面时,我的 API 数据丢失,但我的令牌仍然保存在本地存储中。 Now i don't want to lost my data on refresh my page现在我不想在刷新页面时丢失数据

You could store your data in your localstorage aswell.您也可以将数据存储在本地存储中。 But I don't see why you couldn't just go fetch your data once again.但我不明白为什么你不能只是 go 再次获取你的数据。 The less you store Client side, the better.您存储客户端的越少越好。 Because everything stored client side can be altered by the client.因为客户端可以更改存储在客户端的所有内容。

PS NegativeFriction Is having a great point on reading old data, in the comment. PS NegativeFriction在评论中对阅读旧数据很有帮助。

You could store the data (user list in your case) in the local storage, but I would discourage you from doing that for the following reasons:您可以将数据(在您的情况下为用户列表)存储在本地存储中,但出于以下原因,我不鼓励您这样做:

  1. Local storage is limited and adding a user list will pollute that space for you.本地存储空间有限,添加用户列表会污染您的空间。
  2. Data like user list might need updating regularly.用户列表等数据可能需要定期更新。 It is recommended that you get a fresh list every time.建议您每次都获取一个新列表。

Depending on how complex your app is you can use a state manager like Redux or you can simply store the data you need by converting it to a string and storing it away.根据您的应用程序的复杂程度,您可以使用 state 管理器,例如 Redux,或者您可以通过将其转换为字符串并将其存储起来来简单地存储您需要的数据。 Once your application refreshes fetch this string again from local storage and load it back into your components.一旦您的应用程序刷新,再次从本地存储中获取此字符串并将其加载回您的组件中。

let myData = JSON.stringify(data)
localStorage.setItem('profile_data')

//on page reload
let storedData = JSON.parse(localStorage.getItem('profile_data'))

Have to agree with @Nicolas on refetching your data on client apps.必须同意 @Nicolas 在客户端应用程序上重新获取您的数据。 If its stuff like user profile you are storing then it would be wise to fetch that data every-time a page refreshes.如果您正在存储它的用户配置文件之类的东西,那么每次刷新页面时获取该数据是明智的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM