本文介绍了为什么当我开始使用localStorage时代码停止工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码仅在删除使用localStorage的componentWillMount时有效.用法localStorage会导致错误

The code below is only working when I remove the componentWillMount that uses localStorage. With usage localStorage it gives a mistake

我试图将localStorage的使用移出组件,但这无济于事.我想使用本地存储会以某种方式更改this.state.interests,使其不再是数组.

I tried to move usage of localStorage out of component but it won't help. I suppose that using local storage somehow changes this.state.interests that they stop being an array.

let interests = ["Музыка", "Компьютеры", "Радио"]
let ListOfInterest = React.createClass({
  getInitialState: function() {
    return {value: '', interests: interests};
  },
  componentWillMount() {
    let local = localStorage.getItem('interests')
    if (local) {
      this.setState({interests: local});
    } else {
      localStorage.setItem('interests', this.state.interests)}
  },
  deleteInterest(key) {
    delete interests[key]
    this.setState(this.state) // without this line the page will not re-render
  },
  addInterest() {
    interests.unshift(this.state.value)
    this.setState({value: ''})
  },
  handleChange(event) {
    this.setState({value: event.target.value})
  },
  render() {
    return <div className="interests">
      <b>Интересы</b>
      <br/>
      {this.state.interests.map((int, index) => {
        return <button onClick={() => {
          this.deleteInterest(index)
        }} key={index} className="btn-interest">{int}</button>
      })}
      <input type='text' placeholder="Add" value={this.state.value} onChange={(e) => this.handleChange(e)}/>
      <button onClick={() => {
        this.addInterest()
      }} className="add">Add interest</button>

    </div>
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

推荐答案

示例中有几个问题

    localStorage.setItem第二个参数中的
  1. 必须是String,您不能存储Array(时,由于调用方法toString,所以在存储中将用逗号分隔字符串. -[1, 2, 3].toString() ),则需要 stringify 数组设置为存储"之前

  1. in localStorage.setItem second argument have to be a String, you can not store Array(when you do it, in storage will be string separated by coma because called method toString - [1, 2, 3].toString() ), you need stringify array before set to Storage

localStorage.setItem(
   'interests', JSON.stringify(this.state.interests)
)

parse 获得价值时

and parse when get value

let local = JSON.parse(localStorage.getItem('interests'));

  • this.setState(this.state)这不是更新状态的好方法,您需要像这样的更新状态

  • this.setState(this.state) this is not good way to update state, you need update state like so

    deleteInterest(key) {
      this.setState({
        interests: this.state.interests.filter((el, i) => i !== key)
      })
    },
    
    addInterest() {
      this.setState({ 
        value: '', 
        interests: this.state.interests.concat(this.state.value)
      });
    },
    

  • Example

    这篇关于为什么当我开始使用localStorage时代码停止工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    10-31 20:30