保存在react组件中的localStorage会随着组件的更新而更新吗?

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 (
      <div className={Style.box}>
        <div style={style} className={Style.btn} onClick={this.handleClick.bind(this)} title={'Click to toggle'}>
          You {text} button.
        </div>
        <div> "访问页面次数:{localStorage.pagecount1}次"</div>
      </div>
    );
  }
}
阅读 8.1k
1 个回答

首先你这个不是访问页面次数, 是组件渲染的次数.
其次localStorage是存入了本地,
与组件已经无关了(赋值有关),
组件销毁关闭浏览器都没关系, 只要不清浏览器的浏览数据, 就永远存在.

传送门 : localStorage使用

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题