javascript - 母组件控制子组件的输入,但不会在更改时重新呈现
问题描述
我有一个 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
对象,因此它不会自动更新。
解决方案
你正在改变 React 状态(而 React 根本不喜欢这个)。这可能会引发奇怪的问题,并使事情不会按预期重新渲染。
const labelToUpdate = globalState.filter(entry => entry.value === categoryKey).pop(); Pop 是一种可变方法,尽管我不知道在这种情况下是否有问题,因为 filter 纯粹是功能性的。无论如何,如果您只想要一个元素,则可以使用 find 代替 filter (
const labelToUpdate = globalState.find(entry => entry.value === categoryKey)
),如果有多个元素并且只想要最后一个 (const labelToUpdate = globalState.filter(entry => entry.value === categoryKey).slice(-1)[0]
)函数 updateLabelValue 改变 globalState。事实上,
globalState[index] = labelToUpdate
当您调用 setState 时,您已经更改了状态。
要解决此问题,您可以将元素的索引传递给函数并进行类似的操作
const updateLabelValue = (value, index) =>{
const newState = globalState.map((item, i) => {
if(index === i){ return value }
else{ return item }
}
setGlobalState(newState)
}
推荐阅读
- excel - 为什么我的 Excel VBA 代码不保存打开的 Word 文档?
- java - Uiautomatorviewer 未使用 java 13.0 启动
- r - 在 R 中生成 10x10 绘图的有效方法
- security - 如何按特定日期对 Openvas 报告进行排序?
- python - TypeError:在绘制 seaborn.regplot 时,无法根据规则“安全”将数组数据从 dtype('int64') 转换为 dtype('int32')
- rest-assured - 没有方法签名:静态 io.restassured.internal.http.URIBuilder.encode()
- flutter - 在 dart 中使用条件设置变量
- laravel - 解决解析错误:语法错误,意外的“?” 在 helpers.php 第 500 行
- asp.net - 检查用户会话是否处于活动状态
- ember.js - 为什么这个 Ember 组件被创建了两次?