[英]sessionStorage and localStorage appearently resets when I refresh the page
[英]How can I persist localstorage when ComponentDidMount resets the value on refresh?
從列表中獲取並將其設置為零時,我將一個項目附加到每個數組項目。 然后在 ComponentDidMount() 中運行該函數。
newsList = (category) => {
fetch(API_URL)
.then((response) => response.json())
.then((response) => {
var news = response.articles;
news = news.map((x) => ({ ...x, likes: 0 }));
this.setState({ general: news }, () => {
localStorage.setItem("general", JSON.stringify(this.state.general));
});
});
};
我隨后增加了我附加的“喜歡”值並保存到本地存儲。
generalLikeCount = (x) => {
let newArr = [...this.state.general];
newArr[x]["likes"] = parseInt(newArr[x]["likes"]) + 1;
this.setState({ general: newArr }, () => {
localStorage.setItem("general", JSON.stringify(this.state.general));
});
};
但是在每次刷新時,喜歡計數器都會重置為零。 我不知道如何解決這個問題。
如果有人遇到同樣的問題,我通過檢查本地存儲中是否存在該值並使用該值來解決此問題,或者如果它不存在則對其進行初始化。
像這樣:
if(JSON.parse(localStorage.getItem(category)) !== null || undefined ) {
news = JSON.parse(localStorage.getItem(category));
} else {
news = news.map((x) => ({ ...x, likes: 0 }));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.