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

查看:103
本文介绍了javascript - 保存在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>
    );
  }
}

解决方案

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

传送门 : localStorage使用

这篇关于javascript - 保存在react组件中的localStorage会随着组件的更新而更新吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆