不用Object.assign,改用ES6扩展运算符优化Redux reducer写法可行吗?
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
stateinto a new object, then updating thetodosfield.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

