import React,{PureComponent} from "react";
export class App extends PureComponent{
constructor(){
super()
this.state = {
books:[
{name:"你不知道的JS",price:99,count:1},
{name:"JS高级程序设计",price:88,count:1},
{name:"React高级设计",price:78,count:2},
{name:"Vue高级设计",price:95,count:3},
],
friend:{
name:"kobe"
},
message:"Hello World"
}
}
addNewBook(){
const newBook = { name:"Angular高级设计",price:88,count:1}
// 1.直接修改原有的State,重新设计一遍
// 在PureComponent是不能引入渲染组件(re-render)
this.state.books.push(newBook)
this.setState({books:this.state.books})
// 2.赋值一份books,在新的books中修改,设置新的books
const books = [...this.state.books]
books.push(newBook)
this.setState({books:books})
}
addBookCount(index){
// this.state.books[index].count++
const books = [...this.state.books]
books[index].count++
this.setState({books:books})
}
render(){
const { books } = this.state
return (
<div>
<h2>数据列表</h2>
<ul>
{
books.map((item,index)=>{
return (
<li key={index}>
<span>
name:{item.name}-price:{item.price}-count:{item.count}
<button onClick={e=>this.addBookCount(index)}>+1</button>
</span>
</li>
)
})
}
</ul>
<button onClick={e=>this.addNewBook()}>添加新书籍</button>
</div>
)
}
}
export default App数据不可变的好处
便于数据追踪,不可变数据使得数据的变化历史更加清晰,便于调试和追踪问题。开发者可以更容易地回滚到数据的前一个状态,进行问题排查。
数据不可变的坏处
增加代码复杂度,增加内存开销,增加运行时间。
最后我们附上浏览器上的效果图:

感谢大家观看,我们下次再见!
我热爱 旅游专栏。令人惊艳了解路线。
欣赏你的照片, 我明白, 世界很美。感谢 旅行灵感。
读起来像小说。继续保持 带来的灵感。
让人精神焕发的 帖子! 我准备订票了。
以后焦虑了或者迷茫了记得回来看看
我非常喜欢 出行博客。鼓舞人心查看路线。
你们的博客 百分百 帮助选择路线。坚持!
信息丰富的 出行资源! 越来越棒!
My brother suggested I might like this blog. He was entirely right. This post actually made my day. You cann't imagine just how much time I had spent for this information! Thanks!
我热爱, 写得很实在。你的博客 就是 最好的例子。很出色。