Heim > Fragen und Antworten > Hauptteil
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