Ist es normal, dass sich der Wert von pagecount1, der localStorage in der React-Komponente speichert, nach dem Klicken ändert? Bitte analysieren Sie es.
Der Quellcode lautet wie folgt:
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使用