React useSelector 不起作用,我做错了什么? [英] React useSelector not working, what am I doing wrong?

查看:28
本文介绍了React useSelector 不起作用,我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 selector.js 文件的选择器文件夹

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
}

这是我的 favicon.js 文件,它调用了 useSelector.

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

我不断收到错误消息,说我的选择器不是函数._selectors.isRecipeFavourited 不是函数.我正在尝试从状态中检索 recipe.is_fav 的值.我也在这个项目中使用 Redux.

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.

推荐答案

我认为您需要在选择器函数中反转 staterecipeId ,即:

I think you need to reverse state and recipeId in your selector function, i.e.:

const isRecipeFavorited = recipeId => state => {...}

这是一个有效的useSelector:

const thing = useSelector(state => state.thing);

在您的情况下,您正在使用另一种类型的参数调用一个函数,而该函数又应该返回 useSelector 期望的类型的函数.

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.

这篇关于React useSelector 不起作用,我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆