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 (
      

好友列表

    { this.state.friends.map(item=>{ return (
  • {item.name}-{item.age}
  • ) }) }
) } 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函数

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

事件:

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