按下按钮时 React Native 不更新图标
React Native not updating icon when button is pressed
我正在使用 react-native-vector-icons,我想在按下按钮时更改图标。
const {favorites, toggleFavorite} = useFavorites();
const isFavorite = favorites.includes(value);
return (
...
<Button
icon={
<Icon
name={isFavorite ? 'favorite' : 'favorite-border'}
size={24}
color={theme.colors.text.contrast}
/>
}
onPress={() => toggleFavorite(value)}
type="clear"
/>
export const useFavorites = (): {
favorites: string[];
toggleFavorite: (lineNumber: string) => Promise<void>;
} => {
const [favorites, setFavorites] = useState<string[]>([]);
const readFavorites = async () => {
try {
const value = await AsyncStorage.getItem(FAVORITES_KEY);
setFavorites(value ? value.split(',') : []);
} catch (e) {
console.log(e);
}
};
const toggleFavorite = async (lineNumber: string) => {
let newFavorites = favorites;
if (favorites.includes(lineNumber)) {
newFavorites = newFavorites.filter(favorite => favorite !== lineNumber);
} else {
newFavorites.push(lineNumber);
}
try {
await AsyncStorage.setItem(FAVORITES_KEY, newFavorites.join(','));
setFavorites(newFavorites);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
readFavorites();
}, []);
return {
favorites,
toggleFavorite,
};
};
当我按下按钮时,isFavorite 的值被正确切换。当 isFavorite 最初为 true 时它也有效。反之则不行。我在这里错过了什么?
编辑:为更多上下文添加了 useFavorites
你的问题是你添加项目的方式不对。你不能直接改变状态。像这样更新:
if (favorites.includes(lineNumber)) {
newFavorites = newFavorites.filter(favorite => favorite !== lineNumber);
} else {
newFavorites = [...favorites, lineNumber]
}
我正在使用 react-native-vector-icons,我想在按下按钮时更改图标。
const {favorites, toggleFavorite} = useFavorites();
const isFavorite = favorites.includes(value);
return (
...
<Button
icon={
<Icon
name={isFavorite ? 'favorite' : 'favorite-border'}
size={24}
color={theme.colors.text.contrast}
/>
}
onPress={() => toggleFavorite(value)}
type="clear"
/>
export const useFavorites = (): {
favorites: string[];
toggleFavorite: (lineNumber: string) => Promise<void>;
} => {
const [favorites, setFavorites] = useState<string[]>([]);
const readFavorites = async () => {
try {
const value = await AsyncStorage.getItem(FAVORITES_KEY);
setFavorites(value ? value.split(',') : []);
} catch (e) {
console.log(e);
}
};
const toggleFavorite = async (lineNumber: string) => {
let newFavorites = favorites;
if (favorites.includes(lineNumber)) {
newFavorites = newFavorites.filter(favorite => favorite !== lineNumber);
} else {
newFavorites.push(lineNumber);
}
try {
await AsyncStorage.setItem(FAVORITES_KEY, newFavorites.join(','));
setFavorites(newFavorites);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
readFavorites();
}, []);
return {
favorites,
toggleFavorite,
};
};
当我按下按钮时,isFavorite 的值被正确切换。当 isFavorite 最初为 true 时它也有效。反之则不行。我在这里错过了什么?
编辑:为更多上下文添加了 useFavorites
你的问题是你添加项目的方式不对。你不能直接改变状态。像这样更新:
if (favorites.includes(lineNumber)) {
newFavorites = newFavorites.filter(favorite => favorite !== lineNumber);
} else {
newFavorites = [...favorites, lineNumber]
}