问题描述
下面的代码仅在删除使用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>
推荐答案
示例中有几个问题
-
必须是
String
,您不能存储Array
(时,由于调用方法toString
,所以在存储中将用逗号分隔字符串. -[1, 2, 3].toString()
),则需要stringify
数组设置为存储"之前
localStorage.setItem
第二个参数中的in
localStorage.setItem
second argument have to be aString
, you can not storeArray
(when you do it, in storage will be string separated by coma because called methodtoString
-[1, 2, 3].toString()
), you needstringify
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)
});
},
这篇关于为什么当我开始使用localStorage时代码停止工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!