Use Object.assign or Spread Operator in React/Redux? Which is a better practise

后端 未结 4 397
名媛妹妹
名媛妹妹 2020-11-30 04:32

I have some confusion about using Object.assign for React and Redux.

I read this article.

It says ES6 Does not supported by all browsers but I

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 04:48

    Redux docs recommends you to use the spread operator approach instead of the Object.assign

    As per the docs:

    An alternative approach is to use the object spread syntax proposed for the next versions of JavaScript which lets you use the spread (...) operator to copy enumerable properties from one object to another in a more succinct way. The object spread operator is conceptually similar to the ES6 array spread operator

    The advantage of using the object spread syntax becomes more apparent when you're composing complex objects

    Using the Spread operator syntax

    export const selectDiameter = (scaleData,size) => {
      return {
        type: SELECT_DIAMETER,
        payload: {...scaleData, 
                     diameter: {
                              ...scaleData.diameter,
                               selectedTube: size,
                               isClicked: true,
                               audio: {
                                    ...scaleData.diameter.audio,
                                    isPlayed: true
                               }
                     }
    
                 }
       }
    }
    

    It still uses ES6. See the Redux docs for more info on configuring your code for the same

    However when you are dealing with the nested data. I prefer to use immutability-helpers

    For your code it will be like

    import update from 'immutability-helpers';
    
    export const selectDiameter = (scaleData,size) => {
      return {
        type: SELECT_DIAMETER,
        payload: update(scaleData, {
             diameter: {
                selectedTube: { $set: size},
                isClicked: { $set: true},
                audio: {
                    isPlayed: {$set: true}
                }
             }
        })
       }
    }
    

提交回复
热议问题