Is it normal that the value of pagecount1 that saves localStorage in the react component will change after clicking? Please analyze it.
The source code is as follows:
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>
);
}
}
First of all, this is not the number of page visits, but the number of component renderings.
Secondly, localStorage is stored locally,
It has nothing to do with the component (related to assignment),
It doesn’t matter if the component is destroyed or the browser is closed, as long as the browser is not clear Browse data, it will always be there.
Portal: used by localStorage