日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

React修改數(shù)組對象的注意事項及說明_React

作者:叉叉醬 ? 更新時間: 2022-12-29 編程語言

React修改數(shù)組對象問題

react開發(fā)主張使用函數(shù)式編程,函數(shù)式編程有個重要的特性就是不可變性。

你無法更改數(shù)據(jù),也不能更改。 如果要改變或更改數(shù)據(jù),則必須復制數(shù)據(jù)副本來更改。

看個例子,就是Vue和React兩個框架實現(xiàn)給數(shù)組添加一個元素。

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>
? ? ? ? )
? ? }
}

這里會發(fā)現(xiàn)兩個框架有個細微差別,Vue是直接修改的原數(shù)組,而React是不修改原數(shù)組,而是創(chuàng)建了一份新的數(shù)組,再通過setState賦值。剛接觸React的時候的確會覺得挺奇怪,感覺會無形增加代碼復雜度。接下來看下為何React要如此設計。

React遵循函數(shù)式編程規(guī)范。在函數(shù)式編程中,不推薦直接修改原始數(shù)據(jù)。 如果要改變或更改數(shù)據(jù),則必須復制數(shù)據(jù)副本來更改。所以,函數(shù)式編程中總是生成原始數(shù)據(jù)的轉換副本,而不是直接更改原始數(shù)據(jù)。

這里是一些常見的React修改數(shù)組或者對象的例子,所有這些函數(shù)都不改變現(xiàn)有的數(shù)據(jù),而是返回新的數(shù)組或對象。

刪除數(shù)組中的指定元素

//刪除testArr中的櫻桃
...
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修改數(shù)組中某個參數(shù)值方法

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

原文鏈接:https://blog.csdn.net/weixin_39782183/article/details/104751400

欄目分類
最近更新