react-native - 如何将来自 api 的布尔值切换为 true/false(React Native)?
问题描述
我敢肯定这真的很简单,但我有点挣扎!在我的graphql api中,我有这个:
... on Flux {
__typename
id
subscribed <= This is the boolean I'm trying to toggle
// more fields
}
我有一个包含多个项目的平面列表。每个项目都有一个开关来设置subscribed
字段为真或假。
我的开关是这样的:
<Switch
trackColor={{
false: theme.color.grey,
true: theme.color.primary,
}}
thumbColor={
item.subscribed ? theme.color.grey : theme.color.grey
}
style={{transform: [{scaleX: 0.8}, {scaleY: 0.8}]}}
ios_backgroundColor={theme.color.grey}
onValueChange={() => _onPressItem(item)}
value={item.subscribed} // the default value is the subscribed field from the api.
/>
我的onPress
功能:
const _onPressItem = useCallback(
async (flux) => {
const multiple = flux.__typename === 'FluxGroup';
if (flux.subscribed === true) {
Notifier.showNotification({
title: !multiple
? 'Vous êtes désabonné de ce flux'
: 'Vous êtes désabonné de ce groupe',
Component: CustomNotifierError,
componentProps: {
alertType: 'error',
},
});
if (!multiple) {
await unsubscribeFromFlux({
optimisticResponse: {
__typename: 'Mutation',
unsubscribeFromFlux: {
__typename: 'Flux',
optimistic: true,
id: uuid.v4(),
subscribed: false,
name: flux.name,
description: flux.description,
notification_subscribed: flux.notification_subscribed,
is_activated: flux.is_activated,
image: {
__typename: 'Image',
id: flux.image.id,
uri: flux.image.uri,
},
},
},
variables: {
id: parseInt(flux.id),
},
update: (cache) => {
const id = cache.identify({
id: parseInt(flux.id),
__typename: 'Flux',
});
const fragment = gql`
fragment fluxToSelect on Flux {
subscribed
}
`;
const fluxToSelect = cache.readFragment({fragment, id});
console.log('Cached FluxToSelect: ', fluxToSelect);
const newData = {...fluxToSelect, subscribed: false};
cache.writeFragment({fragment, id, newData});
},
refetchQueries: [
{query: GET_EXPLORER_CATEGORIES_QUERY},
{query: USER_ME_QUERY},
],
awaitRefetchQueries: true,
}).then((response) => {
console.log('response: ', response);
return response;
});
}
// More from it but cut for readability
当我切换开关以将值更改为 时subscribed = false
,它正在工作,但随后它切换回 true 然后再次切换为 false ......当想要将其切换为 时subscribed = true
,它会工作,然后闪烁为 false,然后最终变为 true。
我怎样才能避免这种行为?我尝试使用 useState 之类的东西setSelected({ ...isSelected, [flux.id]: true })
但没有运气,因为我需要我的开关与 api 同步。有什么我想念的吗?
有人能指出我正确的方向吗?:)
解决方案
推荐阅读
- google-sheets - 当 F7 和 I7 给定时间时,如果 A 和 B 之间的时间显示 X
- uwp - C# UWP - DevicePairingKinds.ConfirmOnly 不提供与 DevicePairingKinds 相同的权限 (?)。提供密码
- angular - ngFor 在一个大数组上
- css - 我找不到在 IE 上显示以 CSS 网格开发的网站的解决方案
- php - 更新 json php/laravel 中键的值
- angular - 无法读取未定义 Google 地图的属性“nativeElement”
- laravel - Eloquent 中二级关系的排序
- css - 导航栏方向引导程序 4
- javascript - 如何在主页的“特色”(推荐)模块中连续显示5个产品,而不是4个?
- r - 如何在不使用 dyplr 或 magrittr 管道的情况下在 R Shiny 中使用 debounce