[英]Why the code stops working when I start using localStorage?
下面的代碼僅在刪除使用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>
您的示例中有幾個問題
在localStorage.setItem
第二個參數中必須為String
,您不能存儲Array
( 這樣做時,在存儲中將以逗號分隔字符串,因為調用方法toString
[1, 2, 3].toString()
),您在設置為Storage之前需要stringify
數組
keyValue
一個DOMString,包含要提供要創建/更新的鍵的值。
localStorage.setItem( 'interests', JSON.stringify(this.state.interests) )
獲取價值時parse
let local = JSON.parse(localStorage.getItem('interests'));
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) }); },
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.