【发布时间】:2020-10-02 19:21:56
【问题描述】:
每次用户单击复选框时都会调用 setLabels,从而生成与已选择的 itemId 匹配的项目列表。 (例如,如果选中 1.3,则 for 循环会遍历 exportEntries,获取与键 1.3 匹配的所有对象值)
然后我使用 setState 将 filtersArray 设置为返回的值。但是,下次用户点击另一个复选框时,状态显然会重置。
我将如何维护所有先前选择的值并添加到状态而不是替换当前状态集?
setLabels = (e, itemId, itemLabel) => {
let fillerArray = [];
for (let item of this.state.exportEntries) {
if (itemId in item) {
fillerArray.push({ [itemLabel]: item[itemId] });
}
this.setState({
filteredArray: fillerArray
});
}
console.log(this.state.filteredArray);
e.preventDefault();
}
第一次点击输出
0: {First: "One"}
1: {First: "Two"}
2: {First: "Three"}
3: {First: "Four"}
4: {First: "Five"}
第二次点击输出
0: {Second: "One"}
1: {Second: "Two"}
2: {Second: "Three"}
3: {Second: "Four"}
4: {Second: "Five"}
** 编辑对象数组 **
const singleValue = [...this.state.selectedValues];
for (let item of this.state.exportEntries) {
if (id in item) {
// This is pulling values from exportEntries that match the id
// of the 'label' selected. So 'First', 'Last', etc... all have
// an id that is passed to perform the check here.
singleValue.push({ [label]: item[id] });
}
}
for (var i = 0; i < singleValue.length; i++) {
merged.push({ ...this.state.selectedValues[i], ...singleValue[i]})
}
// This is where I'm trying to merge the two arrays
// If I click First & Last this is returned:
// (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
// 0: {First: "First 1"}
// 1: {First: "First 2"}
// 2: {First: "First 3"}
// 3: {First: "First 4"}
// 4: {First: "First 5"}
// 5: {Last: "Last 1"}
// 6: {Last: "Last 2"}
// 7: {Last: "Last 3"}
// 8: {Last: "Last 4"}
// 9: {Last: "Last 5"}
// I want this:
// (5) [{…}, {…}, {…}, {…}, {…}]
// 0: {First: "First 1" , Last: "Last 1"}
// 1: {First: "First 2", Last: "Last 2"}
// 2: {First: "First 3", Last: "Last 3"}
// 3: {First: "First 4", Last: "Last 4"}
// 4: {First: "First 5", Last: "Last 5"}
【问题讨论】:
-
您确定要在循环中每次运行
setState,而不是在完成构建新数组后运行吗? -
@Auskennfuchs 我肯定会调整结构以包含此评论。但是,我仍然需要以某种方式保留所有以前的选择。无论如何,您是否可以提供一些有关如何保留这些值的文档或示例?
-
@SethSpivey 你能分享codesandbox MVP吗?
-
@DipenShah 这一切都被捆绑成需要特定密钥的部分,并且是一个更复杂的项目的一部分,在沙箱中创建需要花费太多时间。不过,我很乐意解释或提供任何东西。
-
@SethSpivey 确定我根据自己的理解添加了建议。