gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 05:34:33 25 4
gpt4 key购买 nike

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

this.state.interests.map is not a function

我尝试将 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>
}
})
<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>

最佳答案

您的示例中有几个问题

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

    keyValue A DOMString containing the value you want to give the key you are creating/updating.

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

    获取值时为parse

    let local = JSON.parse(localStorage.getItem('interests'));
  2. 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)
    });
    },

Example

关于javascript - 为什么当我开始使用 localStorage 时代码停止工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40788244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com