【发布时间】:2018-08-08 17:32:58
【问题描述】:
这是我的应用程序的简单版本
constructor(props) {
super(props);
let images = JSON.parse(localStorage.getItem('images'))
images = images? images : []
this.match = props.match
// the images part of this state should be handled by the app component but for now i'll use localStorage
console.log('constructor', images);
this.state = {
count: 0,
increment: 9,
images: images
}
if (this.state.images.length === 0) {
this.getImages(this.state);
}
}
build_gallery_items = (images) => {
return images.map((src, id) => {
return (
<div className="item col s4" key={src}>
<a data-fancybox="gallery" href={src} data-caption={`<a href='${src}' download>Download</a>`}>
<img className="image-item" src={src} alt="Stuff about this" />
</a>
</div>
);
});
}
getImages = (state) => {
let url = './server/getImages.php'
axios.post(url, state)
.then(res => {
this.setState({
images: this.state.images.concat(this.build_gallery_items(res.data.images))
}, () => {
localStorage.setItem('images', JSON.stringify(this.state.images))
})
})
.catch(err => {
console.log(err);
})
}
render() {
// console.log('images', this.state.images);
return (
<div className='wrap'>
<h2>Image Gallery</h2>
<div className="container">
<div className='row'>
{this.state.images}
</div>
</div>
</div>
)
}
ajax 调用工作正常,将其存储在本地存储中并显示图像。然后,当我刷新页面以使用本地存储中当前的内容时,我得到“对象无效错误”。这是在我尝试使用它之前在我的控制台中打印出来的内容。
它显然看起来像是一个数组,并且通过放置 .toArray 会导致它未定义。
如何解决我的这个问题。
非常感谢任何帮助。谢谢。
【问题讨论】:
标签: reactjs local-storage