在 React/Redux 中使用 Object.assign 还是 Spread 运算符?哪个是更好的做法 [英] Use Object.assign or Spread Operator in React/Redux? Which is a better practise
问题描述
我对在 React 和 Redux 中使用 Object.assign
有一些困惑.
I have some confusion about using Object.assign
for React and Redux.
我阅读了这篇文章.
它说并非所有浏览器都支持 ES6 但我已经开始使用它了.
It says ES6 Does not supported by all browsers but I have started using it.
我有两个问题:
- 继续使用
Object.assign
是正确的决定吗? - 替代方案是什么?
我的代码
export const selectDiameter = (scaleData, size) => {
return {
type: SELECT_DIAMETER,
payload: Object.assign({}, scaleData, {
diameter: Object.assign({}, scaleData.diameter, {
selected_tube_diameter: size,
is_clicked: true,
audio: Object.assign({}, scaleData.diameter.audio, {
is_played: true
})
})
})
}
}
以上代码的替代方法是什么?
What is the alternative for the above code?
推荐答案
Redux docs 建议您使用扩展运算符方法而不是 Object.assign
Redux docs recommends you to use the spread operator approach instead of the Object.assign
根据文档:
另一种方法是使用提议的对象传播语法对于下一个版本的 JavaScript,它可以让你使用传播(...) 运算符将可枚举属性从一个对象复制到另一个更简洁的方式.对象扩展运算符是概念上类似于 ES6 数组展开运算符
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
使用扩展运算符语法
export const selectDiameter = (scaleData,size) => {
return {
type: SELECT_DIAMETER,
payload: {...scaleData,
diameter: {
...scaleData.diameter,
selectedTube: size,
isClicked: true,
audio: {
...scaleData.diameter.audio,
isPlayed: true
}
}
}
}
}
它仍然使用 ES6.请参阅 Redux 文档,了解有关配置您的更多信息相同的代码
It still uses ES6. See the Redux docs for more info on configuring your code for the same
但是,当您处理嵌套数据时.我更喜欢使用 immutability-helpers
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}
}
}
})
}
}
这篇关于在 React/Redux 中使用 Object.assign 还是 Spread 运算符?哪个是更好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!