我有一个屏幕,用户可以在其中启用/禁用特定的推送通知。当用户按下切换按钮时,正确的切换按钮会更改并且状态正在更新。
我遇到的问题是,在切换发生后,它进行了一些奇怪的排序。观看视频 here (我对视频质量感到抱歉,尝试使用此命令执行它: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 缓存。但我想不出任何原因会导致任何相关问题。
最佳答案
在遍历对象的属性时,JavaScript 不保证属性的顺序。参见 this answer .因此,您无法确定 key 是否以您现在预期的方式返回,这可能会导致渲染时发生随机变化。
因此我的建议是在显示对象键之前主动对其进行排序。例如,按字母顺序对它们进行排序:
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) => ...
关于javascript - 多个 Switch 组件在按下时更改列表元素中的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56361232/