React中不可变力量

通过案例展示问题:一个添加用户信息的案例

import React from 'react'
import './App.css'

class App extends React.Component {
constructor(props){
    super(props);
    this.state = {
        friends:[
            {name:'lilei',age:'20'},
            {name:'lili',age:'18'},
            {name:'tom',age:'16'},
        ]
    }
}   
  render() {
      const {friends} = this.state
    return (
      <div>
          <h2>好友列表</h2>
          <ul>
              {
                  this.state.friends.map(item=>{
                      return (<li key={item.name}>{item.name}-{item.age}</li>)
                  })
              }
          </ul>
          <button onClick={e=>this.insertData()}>添加数据</button>
      </div>
    )
  }
  insertData(){
    //   在开发中不允许这么做 
      const newData = {name:'wy',age:100}
      this.state.friends.push(newData)
      this.setState({
        friends:this.state.friends       
      })                 //直接修改state数据

      //正确操作
      const newDate = [...this.state.friends];    //es6的展开运算符,拷贝一些数据
      newDate.push(newData)
      this.setState({
          friends:newDate
      })
  }
}
export default App;

上述的两个方法中。正确的是不操作原数据、

此外提高性能可以使用PureComponent函数

还有,给每个用户的年龄绑上事件,点击一次加一岁

<button onClick={e=>this.incrementAge(index)}>年龄+1</button>

事件:

incrementAge(index){
    console.log(index);
    const newDate = [...this.state.friends];    //先把之前的数据用展开运算符存起来
    newDate[index].age +=1;                //每点击一次,年龄加一岁
    this.setState({
        friends:newDate                    //最后通过setState函数改变数据
    })
  }

 

posted @ 2022-01-11 20:44  无何不可88  阅读(37)  评论(0)    收藏  举报