【发布时间】:2020-06-04 08:17:51
【问题描述】:
我有一个 React 组件,其中有一个类别数组,我映射并索引来自另一个对象的数据。
const labelComponents = categories.map((category, index) =>{
const data = globalState.filter(systemLabel => systemLabel.value === category.categoryKey).pop()
return(
<Label
key={data && data.text ? data.text + category : category + index}
category={category}
data={globalState.filter(systemLabel => systemLabel.value === category.categoryKey).pop()}
deleteLabel={deleteLabel}
updateLabelValue={updateLabelValue}
/>
)
})
我传入函数updateLabelValue,在其中尝试更新所选对象的特定text 属性。
这个函数可能会被重构,但它现在可以工作。
const updateLabelValue = (categoryKey, value) =>{
const labelToUpdate = globalState.filter(entry => entry.value === categoryKey).pop();
const index = globalState.indexOf(labelToUpdate);
labelToUpdate.text = value;
globalState[index] = labelToUpdate
console.log(globalState)
setGlobalState(globalState)
}
我将 euqal 中的密钥放在 data.text 属性上,所以它会自动更新,但这不会发生
当然,这里的问题是我映射了我的categories,但访问了我的globalState 对象,因此它不会自动更新。
【问题讨论】:
标签: javascript reactjs asynchronous state