React中使用setState迭代数组修改键值失败,求代码排查
Hey there! Let's break down why your data array's key values aren't updating as you expect, and fix the code properly.
First: Fix Syntax Errors in State Initialization
Looking at your constructor, you’re using = instead of : for object literal properties — this is a JavaScript syntax error that will break your component before it even runs. You need to correct all instances where you used = to define object keys:
constructor(props) { super(props); this.state = { data: [ // Changed = to : {key: 0, name: "abc", value: "123"}, // Changed = to : for each key {key: 1, name: "def", value: "456"}, {key: 2, name: "ghi", value: "789"} ] } }
Core Issue: Incorrect map Usage in State Update
The main problem stopping your keys from updating is how you’re using map in the renameArrayKeys method:
- Your current code
item.key= index + 1returns the value of the assignment (which isindex+1, so 1, 2, 3) instead of the modified item object. This means yourdatastate gets replaced with[1,2,3]instead of the array of objects you want. - You’re also directly mutating the original
itemfrom the old state, which is a bad practice in React (state should always be treated as immutable).
Correct the State Update Logic
Instead, return a new object for each item in the array: copy the original item’s properties and overwrite the key with the new value. Here’s the fixed renameArrayKeys method:
renameArrayKeys = () => { // You weren't using the `key` parameter, so we can remove it this.setState(oldState => { return { data: oldState.data.map((item, index) => ({ ...item, // Copy all existing properties of the item key: index + 1 // Overwrite the key with the new value })) } }) }
Full Fixed Component
Putting it all together, your component will work as expected:
class MyApp extends React.Component{ constructor(props) { super(props); this.state = { data: [ {key: 0, name: "abc", value: "123"}, {key: 1, name: "def", value: "456"}, {key: 2, name: "ghi", value: "789"} ] } } renameArrayKeys = () => { this.setState(oldState => { return { data: oldState.data.map((item, index) => ({ ...item, key: index + 1 })) } }) } render() { return( <button onClick={this.renameArrayKeys}> Click Me </button> ) } }
Why This Works
- Immutable Updates: We use the spread operator (
...item) to create a copy of each object instead of modifying the original one, which follows React’s state immutability rules. - Correct
mapReturn Value: Instead of returning just the new key, we return the full modified object, so thedataarray remains an array of objects with updatedkeyvalues. - Fixed Syntax: The initial state is now properly defined with valid JavaScript object literal syntax, so the component runs without errors.
内容的提问来源于stack exchange,提问作者DadyByte

