React修改数组对象的注意事项及说明

2022-12-02 10:09:05

目录React修改数组对象问题React修改数组中某个参数值方法React修改数组对象问题react开发主张使用函数式编程,函数式编程有个重要的特性就是不可变性。你无法更改数据,也不能更改。如果要改...

目录
React修改数组对象问题
React修改数组中某个参数值方法

React修改数组对象问题

react开发主张使用函数式编程,函数式编程有个重要的特性就是不可变性。

你无法更改数据,也不能更改。 如果要改变或更改数据,则必须复制数据副本来更改。

看个例子,就是vue和React两个框架实现给数组添加一个元素。

vue

export default {
 name: "home",
 data() {
  return {
   testArr: ['苹果','香蕉']
  };
  },
  created(){
    this.testArr.push('橘子')
  }
};
...

react

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      testArr: ['苹果','香蕉']
    };
  }
  componentDidMount(){
    this.setState({
      testArr:[...this.state.testArr,'橘子']
    })
  }
  render(){
    return (
      <React.Fragment>
        <p>{this.state.testArr}</p>
      </React.Fragment>
    )
  }
}

这里会发现两个框架有个细微差别,Vue是直接修改的原数组,而React是不修改原数组,而是创建了一份新的数组,再通过setState赋值。刚接触React的时候的确会觉得挺奇怪,感觉会无形增加代码复杂度。接下来看下为何React要如此设计。

React遵循函数式编程规范。在函数式编程中,不推荐直接修改原始数据。 如果要改变或更改数据,则必须复制数据副本来更改。所以,函数式编程中总是生成原始数据的转换副本,而不是直接更改原始数据。

这里是一些常见的React修改数组或者对象的例子,所有这些函数都不改变现有的数据,而是返回新的数组或对象。

删除数组中的指定元素

//删除jstestArr中的樱桃
...
constructor(props) {
  super(props);
  this.state = {
    testArr: ['苹果','香蕉','橘子','樱桃','橙子']
  };
}
componentDidMount(){
  this.setState({
    testArr:this.state.testArr.filter(res=>res!=='樱桃')
  })
}
...

合并两个对象

...
constructor(props) {
  super(props);
  this.state = {
    testObj1:{
      chineseName:'橘子',
      englishName:'orange'
    },
    testObj2:{
      color:'yellow',
      shape:'circle'
    },
    testObj:{}
  };
}
componentDidMount() {
  this.setState({
    testObj: Object.assign(this.state.testObj1,this.state.testObj2)
  })
}
...

修改多层级对象的值

//testObj的apple的color改成green
...
constructor(props) {
  super(props);
  this.state = {
    testObj: {
      banner: {
        name: '香蕉',
        color: 'yellow'
      },
      apple: {
        name: '苹果',
        color: 'red'
      }
    }
  };
}
componentDidMount() {
  this.setState({
    testObj: {
      ...this.state.testObj,
      apple:{
        ...this.state.testObj.apple,
        color:'green'
      }
    }
  })
}
...

React修改数组中某个参数值方法

const currentPageVideoList=[...this.state.currentPageVideoList];
this.setState({currentPageVideoList: currentPageVideoList.map((item, key)=>
  key==index?{...item, coverImg: this.state.defaultImg}:item
)})

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。