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
数据不可变的好处
便于数据追踪,不可变数据使得数据的变化历史更加清晰,便于调试和追踪问题。开发者可以更容易地回滚到数据的前一个状态,进行问题排查。
数据不可变的坏处
增加代码复杂度,增加内存开销,增加运行时间。
最后我们附上浏览器上的效果图:
感谢大家观看,我们下次再见!
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我