gpt4 book ai didi

reactjs - 在 map 函数中 react setState

转载 作者:行者123 更新时间:2023-12-04 14:25:02 25 4
gpt4 key购买 nike

我无法解决下面的问题。

该问题与异步 setState 维度有关。通常我使用回调,但在这里似乎不合适。

我的目标是创建一个状态(我将能够对其进行排序),该状态是通过迭代在 map 中创建的不同状态而获得的。

下面的函数调用了我的不同方法,我们感兴趣的是最后两个。 getUserPointssortArrayforUserRank

getPlayersByUser = () => {
database
.ref(`pools/${this.state.selectedValue}`)
.once("value")
.then(data => {
for (let item in data.val()) {
this.setState({
users: this.state.users.concat([item])
});
this.setState({ [item]: data.val()[item] });
}
})
.then(this.makePlayersArray)
.then(this.getUserPoints)
.then(this.sortArrayforUserRank);


getUserPoints = () => {
this.state.users.map(user => {
// Create the dynamic name of the state, 1 for each user
let userPoints = `${user}points`;

// initializing the state for userPoint to be at 0 for future calculation
this.setState({ [userPoints]: 0 });

this.state[user].map(player => {
database
.ref(`players/${player}`)
.child("points")
.once("value")
.then(data => {
let points = parseInt(data.val());
this.setState(state => ({
[userPoints]: points + state[userPoints]
}));
});
});
});

getUserPoints 允许我动态创建 state.userPoints 汇总来自每个用户的玩家的所有点数。

然后我期待下面的 sortArrayforUserRank 使用更新的 state.userPoints 来创建我的最终 userArrayPoints 状态。

sortArrayforUserRank = () => {
this.state.users.map(user => {
let userPoints = `${user}points`;
this.setState(state => ({
userArrayPoints: state.userArrayPoints.concat([
{ [user]: state[userPoints] }
])
}));
});

目前 userArrayPoints 被 4 个对象 {[user]:0} 填充,而不是每个用户的最终点数总和。问题在于 sortArrayforUserRank 在之前的 setState 完成之前被调用

我很想在 getUserPoints 中使用 setState 回调,但由于我在播放器 map 函数中,它会为每个播放器调用,而我想在用户级别处理它最终的点数总和。

我尝试使用 componentDidUpdate,并根据这些文章让 sur 使用 functionnal setState 但无法弄清楚。

https://medium.com/@shopsifter/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1

https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b

非常感谢您的帮助,

谢谢

最佳答案

你不能用 setState 做你在这里尝试的事情,因为它是异步的,并且会与 for () 循环中每次迭代可用的不同状态发生冲突.

你可以做的是先提取状态,根据需要对其进行操作,然后运行 ​​setState(至少在下面的这个中)

.then(data => {
// Pull out what you want to mess with here first
const users = [ ...this.state.users ];
const dataValObj = data.val();

// Then use spread operator (or Object.assign/Array.concat)
this.setState({
users: [
...users,
...Object.keys(dataValObj)
],
...dataValObj
});
})

而且您似乎在整个代码中遵循了类似的模式。尝试将我在这里所做的应用到使用内部带有 setState 的循环的其他领域。

关于reactjs - 在 map 函数中 react setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47735600/

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