静音 previousState 以在 React 中设置新状态
Muting previousState to set the new State in React
我正在根据 previousState 更改 React 中的状态。基本上我是从项目数组中删除一个项目,我想要最简单的方法。
这很完美,但可能不是最佳做法?
handleItemsRemove = (id, index) => {
if (index === -1) {
return;
}
this.setState(
previousState => {
const { items } = previousState;
items.splice(index, 1);
return {
items
};
}
);
};
在 React 重构 previousState 的方式中,此代码是否存在涉及可变性等的任何问题? previousState
是可变的吗?即使是,也可以吗?
否则,您认为处理这种情况的最佳方式是什么?
方法 splice 修改原始数组 - 所以这不是您需要的方式。
相反,您可以过滤掉不需要的项目。请阅读有关创建新数组的 filter 方法的更多信息。
此外,您不需要为整个状态创建变量。相反,您可以使用 destructuring:
handleItemsRemove = (id, index) => {
if (index === -1) {
return;
}
this.setState(({items}) => ({
items: items.filter((item, itemIndex) => index !== itemIndex),
}));
};
来自React docs:
Never mutate this.state
directly, as calling setState()
afterwards may replace the mutation you made. Treat this.state
as if it were immutable.
我不确定这是否适用于您的情况,但为了安全起见,请构建一个全新的对象。您可以使用 items.slice(0, index)
获取 index
之前的数组部分,使用 items.slice(index + 1)
获取 index
之后的部分,然后 spread 将它们放在新数组中:
handleItemsRemove = (id, index) => {
if (index === -1) {
return;
}
this.setState(
({items}) => ({
items: [
...items.slice(0, index),
...items.slice(index + 1)
]
})
);
};
我正在根据 previousState 更改 React 中的状态。基本上我是从项目数组中删除一个项目,我想要最简单的方法。
这很完美,但可能不是最佳做法?
handleItemsRemove = (id, index) => {
if (index === -1) {
return;
}
this.setState(
previousState => {
const { items } = previousState;
items.splice(index, 1);
return {
items
};
}
);
};
在 React 重构 previousState 的方式中,此代码是否存在涉及可变性等的任何问题? previousState
是可变的吗?即使是,也可以吗?
否则,您认为处理这种情况的最佳方式是什么?
方法 splice 修改原始数组 - 所以这不是您需要的方式。
相反,您可以过滤掉不需要的项目。请阅读有关创建新数组的 filter 方法的更多信息。
此外,您不需要为整个状态创建变量。相反,您可以使用 destructuring:
handleItemsRemove = (id, index) => {
if (index === -1) {
return;
}
this.setState(({items}) => ({
items: items.filter((item, itemIndex) => index !== itemIndex),
}));
};
来自React docs:
Never mutate
this.state
directly, as callingsetState()
afterwards may replace the mutation you made. Treatthis.state
as if it were immutable.
我不确定这是否适用于您的情况,但为了安全起见,请构建一个全新的对象。您可以使用 items.slice(0, index)
获取 index
之前的数组部分,使用 items.slice(index + 1)
获取 index
之后的部分,然后 spread 将它们放在新数组中:
handleItemsRemove = (id, index) => {
if (index === -1) {
return;
}
this.setState(
({items}) => ({
items: [
...items.slice(0, index),
...items.slice(index + 1)
]
})
);
};