You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不用Object.assign,改用ES6扩展运算符优化Redux reducer写法可行吗?

关于Redux Reducer中Object.assign与扩展运算符的写法对比

Great question! I totally get where you're coming from—Object.assign does feel clunky and lacks the elegance of the object spread syntax, so avoiding it when you can is totally a valid preference.

Let's break this down:

两种写法的功能完全等价

First off, both snippets you shared do exactly the same thing: they return a new state object (critical for Redux's immutability rules) that copies all properties from the original state, then overrides the todos array with a new array containing the existing todos plus the new todo item.

From a functionality standpoint, the original Object.assign version is "correct"—it works as intended for a Redux reducer.

为什么早期代码会用Object.assign?

The main reason you might see Object.assign in older Redux code is browser/tooling support. The object spread syntax ({ ...state }) was officially standardized in ES2018; before that, it was just a stage proposal. Back when many projects targeted older browsers or used older Babel configurations that didn't enable support for the spread operator, Object.assign was the reliable go-to way to create immutable copies of objects.

为什么扩展运算符的写法更优?

Your proposed rewrite using the spread operator is absolutely preferable in modern codebases for a few key reasons:

  • Readability: It's more declarative and intuitive. At a glance, you can see we're spreading all properties of state into a new object, then updating the todos field. Object.assign({}, state, {...}) requires mentally parsing the order of arguments (empty object first, then source objects) to understand what's happening.
  • Elegance: It's cleaner and less verbose, especially when dealing with nested state updates (though for deep nesting, libraries like Immer can simplify things even further).
  • Modern convention: Redux's official documentation now favors the spread operator in examples, as it's become the standard approach in modern JavaScript development.

结论

So to answer your question: the original Object.assign写法 is technically valid, but switching to the spread operator version is absolutely appropriate—and recommended! It's a more modern, readable, and elegant way to handle immutable state updates in Redux reducers.

内容的提问来源于stack exchange,提问作者Sharon Chai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:12:32