在React中的onclick事件(不要以爲React導致的問題,我認爲這是我如何處理對象&數組),我試圖抓住一個本地存儲變量並將一個元素(鍵)推送到它,但是它會拋出錯誤'未捕獲的TypeError:無法讀取'null'的屬性'ids'。Javascript推送到本地存儲陣列在React中不工作
下面的代碼:
import React from 'react';
import Images from './images';
export default React.createClass({
getInitialState() {
// If doesn't exist, create empty instance
let selectedImages = localStorage.getItem('selectedImages') ? localStorage.getItem('selectedImages') : { ids : [] };
return selectedImages;
},
selectImage(key) {
// get localstorage
let selectedImages = localStorage.getItem('selectedImages');
// Create instance of ids array and push key
let selectedImagesArray = selectedImages.ids.push(key);
// set .ids as selectedImagesArray
selectedImages.ids = selectedImagesArray;
// Set new local storage
localStorage.setItem('selectedImages', selectedImages);
},
render() {
let selectedImages = localStorage.getItem('selectedImages');
return (
<Images items={feedData.items}
selected={selectedImages}
selectImage={this.selectImage} />
)
}
});
看起來像'localStorage.getItem('selectedImages');''返回'null',所以當然''ids'不能從'null'訪問。另外,你知道'push'返回數組長度的權利?不是真正的陣列。 – azium
'localStorage'只能保存字符串..你必須JSON序列化 – Matt