下述代码是否修改了State?该写法能否用于React setState?
Answer to Your Two Questions
Question 1: Does the second line modify the original State?
Nope, it doesn’t mutate the original state object at all. Here’s the breakdown:
- The first line creates an object
{ a:1, b:2, c:3 }and assigns it to thestatevariable. - The second line uses the spread operator (
...) to generate a brand new object that copies all properties from the originalstate, then overrides thecproperty to 4. Finally, it reassigns this new object to thestatevariable.
Your example code confirms the original state stays intact:
let state = { a: 1, b: 2, c: 3 }; let old = state; state = { ...state, c: 4 }; let newState = state; console.log(old); // {a: 1, b: 2, c: 3} (original state remains unchanged) console.log(newState); // {a: 1, b: 2, c: 4} (new state object created)
Since old holds a reference to the original object, logging it shows the original values—proof the initial state wasn’t modified.
Question 2: Can this写法 be used in React setState scenarios?
Absolutely, and it’s actually a recommended pattern for maintaining immutability in React!
React relies on state changes (via setState in class components or state setters from useState in functional components) to trigger re-renders. To ensure React detects state changes correctly, you should always return a new state object instead of mutating the existing one—which is exactly what your code does.
Here’s how to adapt it for different React setups:
- Class components:
this.setState({ ...this.state, c: 4 }); - Functional components with
useState:
If the new state doesn’t depend on the previous state directly, you can use:
If the new state relies on the latest previous state (common in event handlers or async operations), use the functional update form to avoid stale state issues:setState({ ...state, c: 4 });setState(prevState => ({ ...prevState, c: 4 }));
This immutability pattern helps React efficiently compare state changes and keeps your component behavior predictable.
内容的提问来源于stack exchange,提问作者rnk

