【问题标题】:Why state update one click after with flat list为什么使用平面列表后一键更新状态
【发布时间】:2020-12-06 23:22:10
【问题描述】:

为了简化问题:我有三种状态

  1. ma​​ssageType - 用户选择了按摩类型。
  2. avHoursInDay - 检查当天点击的所有可用时间。
  3. avHoursByType - 操作 avHoursInDay 数组并更改时间取决于用户选择的“massageType”。(因为按摩类型有不同的长度,所以可用时间取决于按摩类型)。

问题:为什么我的状态会延迟一键更改。(示例在最后)

功能 1 - 处理可用时间:

    const handleDay = day => {
    setSelectedDay(day);
    const dayMeetings = weekMeetings.filter(meet => meet.startDate.split("T")[0] === day.dateString);
    let availableHours = hours.map(e => ({ ...e }));
    for (let i = 0; i < dayMeetings.length; i++) {
        for (let j = 0; j < hours.length; j++) {
            if (moment(dayMeetings[i].startDate).format("LT") === hours[j].time) {
                availableHours[j].busy = true;
                availableHours[j + 1].busy = true;
                if (dayMeetings[i].massageType === "sweden" || dayMeetings[i].massageType==="fullbody" ) {
                    availableHours[j + 2].busy = true;
                }
                break;
            }
        }
    }

    setAvHoursInDay(availableHours);
    setAvHoursByType([]);
    if (massageType.key !== -1) massageTypeHandler(massageType);

};

功能 2 - 根据按摩类型控制可用时间:

    const massageTypeHandler = item => {
    setMassageType(item);
    let mapDateByType = avHoursInDay.map(e => ({ ...e }));
    for (let i = 0; i < avHoursInDay.length; i++) {
        if ((i === avHoursInDay.length - 3 && avHoursInDay[i].busy === false && item.key === 2) || item.key === 3) {
            mapDateByType[i].busy = true;
        }
        if (i === avHoursInDay.length - 1 || i === avHoursInDay.length - 2) {
            mapDateByType[i].busy = true;
        } else if (avHoursInDay[i].busy === false) {
            if (avHoursInDay[i + 1].busy === true) {
                mapDateByType[i].busy = true;
            } else if ((item.key === 2 || item.key === 3) && avHoursInDay[i + 2].busy === true) {
                mapDateByType[i].busy = true;
            }
        }
    }
    setAvHoursByType(mapDateByType);
};

=========================

现在我有 flatList ,当用户单击它转到功能 2 时:

    renderItem={({ item }) => (
                    <StyledButton
                        key={item.key}
                        onPress={() => massageTypeHandler(item)}
                        buttonStyle={
                            item.key === massageType.key
                                ? [styles.massagetypebutton, styles.selectedbutton]
                                : styles.massagetypebutton
                        }
                        text={item.massageType}
                    />
                )}
                keyExtractor={item => item.key.toString()}
            />

以及转到函数 1 的日历(也调用函数 2):

<Calendar
            minDate={new Date()}
            markedDates={{
                [selectedDay.dateString]: {
                    selected: true,
                    disableTouchEvent: true,
                },
            }}
            theme={calendarTheme}
            onDayPress={handleDay}
            style={{ marginTop: 10 }}
        />
        {selectedDay && (
            <Text style={styles.daytitle}>יום {moment(selectedDay.dateString).format("dddd  DD/MM/YYYY")}</Text>
        )}
        <AvailableHours avHoursInDay={avHoursByType} />

扩展中的问题: 一切正常,状态更改为正确的可用位置。 但每次渲染更改后只需单击一次。 例如:

  • 首先我点击日期 7 -> 给了我一个空数组,
  • 点击日期 8 -> 给了我日期 7 的可用时间
  • 点击日期 15-> 给了我日期 8 的可用信息

最近更新了一些东西..

请帮忙,提前谢谢,

  • 在图片中你可以看到我在日期 10 和可用的地方 从日期 8(在 10 之前点击),下一次点击我会得到 日期 10 可用。

(如果你看到比两个这么长的函数更快的方法,如果你能给我一个代码审查,我会很高兴)

【问题讨论】:

  • 有点难以理解您的代码在做什么,您能否包含一个Minimal, Complete, and Reproducible 代码示例,也许还有一个重现问题的running 代码框?这通常发生在您尝试访问排队状态更新时,即 您 认为它是来自 next 渲染周期的状态,但实际上它仍然是当前渲染周期的状态。
  • 所以在检查之后我意识到问题是可能第一个负责“setAvHoursInDay”的函数在涉及到第二个函数时不足以改变。有没有办法在渲染之前改变“setAvHoursInDay”的状态?

标签: javascript reactjs react-native use-state


【解决方案1】:

lift-state-up 并使用useReducer 以便同时操作多个状态字段。

function FooCalendar() {
  const [state, action] = useReducer(
      /* your initial state & implementation, move your BL logic to the reducer */
      )  
    // pass the state to your components
    const { selectedDay, avHoursByType } = state;
  return (
    <>
      <Calendar
        minDate={new Date()}
        markedDates={{
          [selectedDay.dateString]: {
            selected: true,
            disableTouchEvent: true,
          },
        }}
        theme={calendarTheme}
        onDayPress={(day) => {
            action({payload: {day}, type: 'DATE_CHANGED' })}
        }
        style={{ marginTop: 10 }}
      />
      {selectedDay && (
        <Text style={styles.daytitle}>
          יום {moment(selectedDay.dateString).format('dddd  DD/MM/YYYY')}
        </Text>
      )}
      <AvailableHours avHoursInDay={avHoursByType} onMessageTypeChanged={(item) => {
        action({payload: {item}, type: 'MESSAGE_TYPE_CHANGED' })
      }} />
    </>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多