gpt4 book ai didi

javascript - 根据服务器响应将State设置为数组

转载 作者:行者123 更新时间:2023-12-01 01:27:11 25 4
gpt4 key购买 nike

我的状态有以下数据结构

this.state = {
days: [
{ day: "Monday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Tuesday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Wednesday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Thursday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Friday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Saturday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Sunday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
],
}

我期待服务器以相同格式的 availities 数组(来自 props)做出响应。

如果接收到的数组的日期匹配,我想覆盖并设置状态为仅返回的那些日期。其余保持不变。例如,如果响应是:

 { day: "Monday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30 },

我想将 State 设置为 days 数组的第一个元素,并覆盖 fromHour、toHour、fromMin、toMin 并将 available 设置为 true。这是我的下面,以及我目前陷入困境的 setState。帮助或建议?

setAvailabilities() {
const { availabilities } = this.props;
const { days } = this.state;
const weekday = [];
const daysAailable = [];


for (i = 0; i < availabilities.length; i++) {
for (j = 0; j < days.length; j++) {
if (days[j].day === availabilities[i].day) {
this.setState({
...this.state.days,
//stuck here
})
}
}
}
}

最佳答案

您所在州的数据结构是:

interface State {
days: Day[]
}

但是在 this.setState 调用中,您将数组分布在整个状态中,而不是替换数组。所以你最终会得到这样的结果:

state = {
days: [...],
0: { day: "Monday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
1: { day: "Tuesday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
// etc...
}

无论如何...

我建议构建一个新数组并立即设置整个日期数组,而不是为每个更新的日期调用 this.setState:

setAvailabilities() {
const { availabilities } = this.props;
const { days } = this.state;

const nextDays = [...days]

for (i = 0; i < availabilities.length; i++) {
for (j = 0; j < nextDays.length; j++) {
if (nextDays[j].day === availabilities[i].day) {
nextDays[j] = availabilities[i]
}
}
}

this.setState({ days: newDays })
}

关于javascript - 根据服务器响应将State设置为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53672446/

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