首页 > 解决方案 > 按下时,多个 Switch 组件在 List 元素中更改顺序

问题描述

我有一个屏幕,用户可以在其中启用/禁用特定的推送通知。当用户按下切换按钮时,正确的切换按钮被更改并且状态正在更新。

我遇到的问题是,在切换发生后,它做了一些奇怪的排序。在此处查看视频(我对视频质量感到抱歉,尝试使用此命令执行它:)xcrun simctl io booted recordVideo toggle.mp4

组件状态

state = {
    defaultNotifications: {
      config_error: { active: true, normalized: 'Notifiy on configuration error' },
      on_first_start: { active: true, normalized: 'Notifiy on first start' },
      on_trigger: { active: true, normalized: 'Notifiy on trigger' },
      on_panic_start: { active: true, normalized: 'Notifiy on panic start' },
      on_panic_end: { active: true, normalized: 'Notifiy on panic sell end' },
      order_placed: { active: true, normalized: 'Notifiy on order placed' },
      trade_completed: { active: true, normalized: 'Notifiy on trade completed' },
      order_cancelled: { active: true, normalized: 'Notifiy on order cancelled' },
    }
  }

切换功能

const enabledNotifications = [];
const stateNotifications = this.state.defaultNotifications;
Object.keys(stateNotifications).forEach((notification) => {
  if (stateNotifications[notification].active) {
    enabledNotifications.push(notification);
  }
});

稍后我需要一个带有“活动”通知名称的逗号分隔字符串用于 POST 请求:

const requestBody = qs.stringify({
  player_id: this.state.playerId,
  permissions: enabledNotifications.toString()
}, { arrayFormat: 'comma', encode: false });

将切换开关更改为 !active

toggleNotification = (notification) => {
    this.setState({ defaultNotifications: {
      ...this.state.defaultNotifications,
      [notification]: {
        ...this.state.defaultNotifications[notification],
        active: !this.state.defaultNotifications[notification].active,
      }
    } });
  };

在 JSX 中切换

    const userNotifications = this.state.defaultNotifications;

    return (
      Object.keys(userNotifications).map((notification) =>
        <ListItem
        key={notification}
        >
          <Image
            style={{ width: 24, height: 24 }}
            source={require('../../../assets/more_icons/notify_green.png')}
          />
          <Text style={styles.notificationText}>
            { userNotifications[notification].normalized }
          </Text>
          <Switch
             onValueChange={() => this.toggleNotification(notification)}
             value={userNotifications[notification].active}
             style={{ marginLeft: 'auto' }}
           />
        </ListItem>
      )
    );

xcrun simctl erase all我记得在此错误发生前几分钟,我确实使用 清除了 XCode Simulator 缓存。但我想不出任何原因会导致任何相关问题。

标签: javascriptreact-native

解决方案


JavaScript 在遍历对象的属性时不保证属性的顺序。看到这个答案。因此,您无法确定密钥是否以您现在预期的方式返回,这可能会导致渲染时发生随机变化。

所以我的建议是在显示对象键之前主动订购它们。例如,按字母顺序对它们进行排序:

Object.keys(userNotifications).sort().map((notification) => ...

或者,您可以使用自己设置的有序数组:

['config_error', 'on_first_start', 'on_trigger', 'on_panic_start', 'on_panic_end', 'order_placed', 'trade_completed', 'order_cancelled'].map(key => userNotifications[key]).map((notification) => ...

推荐阅读