【发布时间】:2016-11-24 22:21:44
【问题描述】:
以下代码仅在我删除使用 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>
}
})
<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>
【问题讨论】:
-
您必须先对数组进行字符串化,然后再将其存储到本地存储中,并在返回时对其进行解串(解析)。
-
this.setState(this.state)看起来很糟糕! -
检查你在componentWillMount()中的本地是否是一个数组
-
你在和stackoverflow.com/questions/40788157/…的作者合作吗?
-
这没有提供问题的答案。一旦你有足够的reputation,你就可以comment on any post;相反,provide answers that don't require clarification from the asker。 - From Review
标签: javascript reactjs local-storage