react元件中儲存了localStorage的pagecount1的值點擊後會改變是正常的嗎?請大神分析一下。
原始碼如下:
import React, { Component } from 'react'
import ReactDom from 'react-dom'
import Style from './main.css'
export default class LikeButton extends Component {
constructor() {
super();
this.state = {
liked: false
};
}
handleClick() {
this.setState({liked: !this.state.liked});
}
render() {
const text = this.state.liked ? 'liked' : 'haven\'t liked';
const style = this.state.liked ? { background: '#8aa'} : {};
localStorage.pagecount1 = localStorage.pagecount1 ? Number(localStorage.pagecount1) + 1 : 1;
return (
<p className={Style.box}>
<p style={style} className={Style.btn} onClick={this.handleClick.bind(this)} title={'Click to toggle'}>
You {text} button.
</p>
<p> "访问页面次数:{localStorage.pagecount1}次"</p>
</p>
);
}
}
首先你這個不是訪問頁面次數, 是組件渲染的次數.
其次localStorage是存入了本地,
與組件已經無關了(賦值有關),
組件銷毀關閉瀏覽器都沒關係, 只要不清瀏覽器的瀏覽數據, 就永遠存在.
傳送門 : localStorage使用