React useSelector not working, what am I doing wrong?

半城伤御伤魂 提交于 2021-02-11 12:45:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!