通过单击“更多”按钮将数组存储在本地存储中2个新闻已添加到DOM 我应该如何实现呢?
const ARR= [
{
id: 1,Name: 'Name1',text:'lorem ipsum'
},{
id: 2,Name: 'Name2',text:'lorem ipsum'
},{
id: 3,Name: 'Name3',{
id: 4,Name: 'Name4',];
10 obj
在这里,我们将数组保存在localStorage中 以及在何处执行其JSON.parse(localStorage.getItem('news')),我不了解如何通过单击来实现与本地存储的协作 ``` localStorage.setItem('news',JSON.stringify(ARR));
class NewsOne extends PureComponent {
constructor() {
super();
this.state = {
listItem: ARR,formAdd: false,};
this.createItem = this.createItem.bind(this);
this.updateItem = this.updateItem.bind(this);
this.removeItem = this.removeItem.bind(this);
this.addForm = this.addForm.bind(this);
}
updateItem(item) {
const { listItem } = this.state;
this.setState({
listItem: listItem.map(elem => (
elem.id === item.id ? item : elem
))
});
}
removeItem(itemId) {
const { listItem } = this.state;
this.setState({
listItem: listItem.filter(item => item.id !== itemId)
});
}
createItem(item) {
const { listItem } = this.state;
this.setState({
listItem: [item,...listItem],});
}
addForm() {
const { formAdd } = this.state;
this.setState({
formAdd: !formAdd,})
}
render() {
const { listItem,formAdd } = this.state;
return(
<>
<div classname="box">
<Title />
<List
data={listItem}
removeFromProps={this.removeItem}
updateFromProps={this.updateItem}
/>
</div>
<button classname ="addnews" onClick = {this.addForm}>
Add
</button>
</>
);
}
}
默认在页面上显示2个元素的类。 我在这里尝试与localStorage中的数组进行交互,但是失败
class List extends PureComponent {
constructor() {
super();
this.state = {
count: 2,}
this.addObj = this.addObj.bind(this);
}
addObj() {
const { count } = this.state;
this.setState({
count: count + 2,});
}
render() {
const { count } = this.state;
const { data } = this.props;
return(
<>
<ul>
{
data.slice(0,count).map(item => (
<>
<Item
key={item.id}
item={item}
/>
</>
))
}
</ul>
<button classname ="addnews" onClick = {this.addObj}>
More
</button>
</>
);
}
}