问题
I have a selectors folder with the selector.js file
const isRecipeFavorited = state => recipeId => {
const recipe = state.find(recipe => recipe.id === recipeId)
console.log(`Selector isRecipeFavourtied: ${recipeId}`)
return recipe ? recipe.is_fav : false
}
This is my favicon.js file which calls this useSelector.
import React, {useState, useEffect} from 'react'
import { FontAwesome } from '@expo/vector-icons'
import { View, TouchableOpacity,StyleSheet, Text, Alert } from 'react-native'
import {isRecipeFavorited} from '../selectors/selectors'
import {useSelector} from 'react-redux'
import { favids } from '../reducers/favids'
const FavIcon = ({recipeid, onToggle, isFavourite, text}) => {
const isFavNew = useSelector(isRecipeFavorited(recipeid))
return (
<View>
<TouchableOpacity style={styles.favItem} onPress={() => onToggle(recipeid)}>
<FontAwesome name={isFavNew === true ? 'heart' : 'heart-o'} size={40} color='red' />
<Text> {text}</Text>
</TouchableOpacity>
</View>
)
}
export default FavIcon
I keep getting an error saying my selector is not a function. _selectors.isRecipeFavourited is not a function. I am trying to retrieve the value of the recipe.is_fav from the state. I am also using Redux in this project.
回答1:
I think you need to reverse state
and recipeId
in your selector function, i.e.:
const isRecipeFavorited = recipeId => state => {...}
This is a valid useSelector:
const thing = useSelector(state => state.thing);
In your case, you're calling a function with another type of argument, which in turn should return a function of the type that useSelector
is expecting.
回答2:
This is solved by drilling down into the favids object.
The selector function has been modified as below.
const recipe = state.favids.find(recipe => recipe.recipeid === recipeId)
return recipe ? recipe.is_fav : false
}```
来源:https://stackoverflow.com/questions/66037525/react-useselector-not-working-what-am-i-doing-wrong