P粉7983434152023-08-24 12:39:53
您可以使用更新
不變性助手來實現此目的: p>
this.setState({ items: update(this.state.items, {1: {name: {$set: 'updated field name'}}}) })
或者,如果您不關心是否能夠使用===
在shouldComponentUpdate()
生命週期方法中檢測此項目的更改,則可以編輯狀態直接並強制元件重新渲染- 這實際上與@limelights 的答案相同,因為它將物件拉出狀態並對其進行編輯。
this.state.items[1].name = 'updated field name' this.forceUpdate()
後期編輯新增:
#查看簡單元件通訊 react-training 中的課程,了解如何將回呼函數從持有狀態的父元件傳遞到子元件的範例需要觸發狀態變更。
P粉7093078652023-08-24 12:38:33
以下是在沒有輔助函式庫的情況下如何做到這一點:
handleChange: function (e) { // 1. Make a shallow copy of the items let items = [...this.state.items]; // 2. Make a shallow copy of the item you want to mutate let item = {...items[1]}; // 3. Replace the property you're intested in item.name = 'newName'; // 4. Put it back into our array. N.B. we *are* mutating the array here, // but that's why we made a copy first items[1] = item; // 5. Set the state to our new copy this.setState({items}); },
如果需要,您可以合併步驟 2 和 3:
let item = { ...items[1], name: 'newName' }
或你可以在一行中完成整個事情:
this.setState(({items}) => ({ items: [ ...items.slice(0,1), { ...items[1], name: 'newName', }, ...items.slice(2) ] }));
注意:我將 items
建立為一個陣列。 OP使用了一個物件。但是,概念是相同的。
您可以看到終端機/控制台中發生了什麼:
❯ node > items = [{name:'foo'},{name:'bar'},{name:'baz'}] [ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ] > clone = [...items] [ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ] > item1 = {...clone[1]} { name: 'bar' } > item1.name = 'bacon' 'bacon' > clone[1] = item1 { name: 'bacon' } > clone [ { name: 'foo' }, { name: 'bacon' }, { name: 'baz' } ] > items [ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ] // good! we didn't mutate `items` > items === clone false // these are different objects > items[0] === clone[0] true // we don't need to clone items 0 and 2 because we're not mutating them (efficiency gains!) > items[1] === clone[1] false // this guy we copied