我在React组件中定义了这两个方法:
handleAddMetric() {
const metricKey = prompt('Name/key of metric');
const newMetricItem = {
name: metricKey,
value: 100
}
let newMetrics = {};
newMetrics[metricKey] = newMetricItem;
const updatedMetrics = Object.assign({}, this.state.metrics, newMetrics);
this.setState({ metrics: updatedMetrics });
}
handleRemoveMetric(keyName) {
let updatedMetrics = this.state.metrics;
delete updatedMetrics[keyName];
console.log('handleRemoveMetric', this, keyName, updatedMetrics);
this.setState({ metrics: updatedMetrics });
}
向this.state.metrics
添加新值可以正常工作,但删除:
<button onClick={this.handleRemoveMetric.bind(this, key)}>Delete</button>
...调用我的handleRemoveMetric
函数,但不更新集合。
我首先是this
的问题,但似乎并非如此。
有什么想法吗?
更新:控制台输出为:
handleRemoveMetric Metrics {props: Object, context: Object, refs: Object, updater: Object, state: Object…}componentWillUnmount: function ()context: Objectprops: Objectref: Objectrefs: ObjectsetState: function (data, cb)state: Objectupdater: Object_reactInternalInstance: ReactCompositeComponentWrapperisMounted: (...)replaceState: (...)__proto__: ReactComponent
"myMetricKey"
Object {MRR: Object, moneyInBank: Object, wow: Object}
...所以至少集合在本地更新。
答案 0 :(得分:1)
您需要将其复制到新对象。
const metrics = {
...this.state.metrics,
[keyName]: null
};
this.setState({ metrics });
应该有用。