如何将state的值赋值给另一个对象?赋值失败求排查建议
allMap Correctly Hey there! Let's break down what's going on here. The root issue is how JavaScript handles object references—your current attempts are either copying the reference to the state object (not the actual values) or doing a shallow copy that might still share references if your state has nested data.
Let's look at why each of your attempts didn't work as expected:
allMap[hash] = this.state: This assigns a reference to the original state object. When you callthis.reset()and update the state,allMap[hash]points to the same object, so it gets modified too.Object.assign({}, this.state)orallMap[hash] = {...this.state}: These are shallow copies. They work fine if your state only contains primitive values (strings, numbers, booleans), but if your state has nested objects or arrays, those nested items are still references. So modifying nested state later would change the value inallMap.allMap[hash] = this.state: Same problem as the first one—direct reference assignment.
Here are the fixes you can try:
1. Use a deep copy for state objects
If your state has nested structures (or you want to be safe even if it doesn't), you need to create a full deep copy to break all references. Here are a few ways:
- JSON-based deep copy (simple, works for most basic data):
Note: This won't work if your state contains functions,allMap[hash] = JSON.parse(JSON.stringify(this.state));Symbolvalues, or circular references. - Manual deep copy (for complex state with nested objects):
If you know your state's structure, you can copy nested properties explicitly:allMap[hash] = { ...this.state, // Example: if you have a nested address object address: { ...this.state.address } }; - Lodash's
_.cloneDeep()(if you have Lodash in your project):allMap[hash] = _.cloneDeep(this.state);
2. Double-check your reset() method
Make sure reset() updates the state using setState (not direct mutation of this.state). Directly modifying this.state is a React anti-pattern and can cause unexpected side effects with references. Your reset should look something like this:
reset = () => { this.setState({ hash: '', firstName: '', lastName: '', // Add other initial state values here }); }
3. Verify the copy works
Add console logs to confirm the value is saved correctly before and after resetting:
addInfo = () => { const hash = this.state.hash; if (this.state.firstName && this.state.lastName) { allMap[hash] = JSON.parse(JSON.stringify(this.state)); console.log('Saved to allMap:', allMap[hash]); // Check the saved value this.reset(); console.log('After reset, allMap still has:', allMap[hash]); // Verify it didn't change } else { alert("please fill the required fields"); } }
内容的提问来源于stack exchange,提问作者Adeola

