当我开始使用localStorage时,为什么代码停止工作?

时间:2016-11-24 13:56:02

标签: javascript reactjs local-storage

以下代码仅在我删除使用localStorage的componentWillMount时才有效。使用localStorage会出错:

  

this.state.interests.map不是函数

我试图将localStorage的使用移出组件,但它没有帮助。我想使用本地存储会以某种方式改变this.state.interests,它们不再是一个数组。



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>
  }
})
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您的示例中有几个问题

    {li>

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

      

    keyValue包含您要提供的值的DOMString   你正在创建/更新的关键。

    localStorage.setItem(
       'interests', JSON.stringify(this.state.interests)
    )
    
    获取值时

    parse

    let local = JSON.parse(localStorage.getItem('interests'));
    
  1. this.setState(this.state)这不是更新状态的好方法,你需要像这样更新状态

    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)
      });
    },
    
  2. Example