gpt4 book ai didi

javascript - 即使我将状态分散到变量中,是否也需要使用 PrevState?

转载 作者:行者123 更新时间:2023-12-01 00:07:04 26 4
gpt4 key购买 nike

我正在测试一些代码,以尝试理解有关使用 setState()竞争条件

我的代码可以找到here

我的代码如下:

import React from "react";

export default class App extends React.Component {
state = {
id: "",
ids: [{ id: 7 }, { id: 14 }]
};

// here is where I create the id numbers
uniqueIdCreatorHandler = incrementAmount => {
let ids = [...this.state.ids];
let highestId = 0;
if (ids.length > 0) {
highestId = ids
.map(value => {
return value.id;
})
.reduce((a, b) => {
return Math.max(a, b);
});
}
let newId = highestId + incrementAmount;
ids.push({ id: newId });
this.setState({ ids: ids });
};

idDeleterHanlder = currentIndex => {
let ids = this.state.ids;
ids.splice(currentIndex, 1);
this.setState({ ids: ids });
};
//below is when I test performing the function twice, in order to figure if the result would be a race condition
double = (firstIncrementAmount, secondIncrementAmount) => {
this.uniqueIdCreatorHandler(firstIncrementAmount);
this.uniqueIdCreatorHandler(secondIncrementAmount);
};

render() {
let ids = this.state.ids.map((id, index) => {
return (
<p onClick={() => this.idDeleterHanlder(index)} key={id.id}>
id:{id.id}
</p>
);
});

return (
<div className="App">
<button onClick={() => this.uniqueIdCreatorHandler(1)}>
Push new id
</button>
<button onClick={() => this.double(1, 2)}>Add some Ids</button>
<p>all ids below:</p>
{ids}
</div>
);
}
}

在第二个按钮上调用double函数时,只有secondIncrementAmount起作用。您可以通过更改 onClick 方法调用的参数值来测试它。

我认为我应该以某种方式在 this.setState 上使用 prevState 来解决这个问题。

我该如何避免这个问题? This matter started at CodeReview但我没有意识到如何解决这个问题。

还有一项建议将映射的 id 传播到 Math.max 中,但我不知道如何以及为什么这样做。通过映射分散的键值来创建新的数组还不够安全吗?

最佳答案

.splice.push 改变数组。因此,当前状态不再与当前渲染的版本匹配。相反,使用 .slice (或 .filter)和 [...old, new] 进行不可变状态更新:

 deleteId = index => {
this.setState(({ ids }) => ({ ids: ids.filter((id, i) => i !== index) }));
};

uniqueIdCreatorHandler = increment => {
const highest = Math.max(0, ...this.state.ids.map(it => it.id ));
this.setState(({ ids }) => ({ ids: [...ids, { id: highest + increment }] }));
};

关于javascript - 即使我将状态分散到变量中,是否也需要使用 PrevState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60308937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com