Javascript 将函数作为道具传递会导致错误吗?
我将一个函数(toggleFavoriteAction)作为道具传递给RecipeListItem组件。当我点击按钮调用函数时,我得到以下错误:TypeError:toggleFavoriteAction不是一个函数。但toggleFavoriteAction确实是一个函数Javascript 将函数作为道具传递会导致错误吗?,javascript,reactjs,typescript,types,Javascript,Reactjs,Typescript,Types,我将一个函数(toggleFavoriteAction)作为道具传递给RecipeListItem组件。当我点击按钮调用函数时,我得到以下错误:TypeError:toggleFavoriteAction不是一个函数。但toggleFavoriteAction确实是一个函数 //RecipeList const-toggleFavoriteAction=(配方:RecipeConfig)=>{ 返回收藏夹。包括(配方) ?调度(添加到配方) :分派(从收藏夹(配方)中移除); }; 常量道具=
//RecipeList
const-toggleFavoriteAction=(配方:RecipeConfig)=>{
返回收藏夹。包括(配方)
?调度(添加到配方)
:分派(从收藏夹(配方)中移除);
};
常量道具={
切换FavoriteAction,
最爱,
};
返回(
{recipes.results&&
Array.isArray(recipes.results)&&
recipes.results.map((数据:RecipeConfig,键:number)=>(
))}
);
//RecipeListItem
常量RecipeListItem=(配方:RecipeConfig,道具:any):JSX.Element=>{
const{toggleFavoriteAction,favorites}=props;
...
......
toggleFavoriteAction(配方)}>//此按钮
{favorites&&favorites.find((fav:any)=>fav.id==recipe.id)
“从fav中移除”
:“添加到fav”}
我认为问题在于如何访问属性
// RecipeListItem
const RecipeListItem = (recipe: RecipeConfig, props: any): JSX.Element => { //here is wrong
const { toggleFavoriteAction, favorites } = props;
...
......
<button onClick={() => toggleFavoriteAction(recipe)}> // this button
{favorites && favorites.find((fav: any) => fav.id === recipe.id)
? 'Remove from fav'
: 'Add to fav'}
</button>
我认为,
RecipeConfig
也是props
对象的一部分,不应该有第二个参数,可能您的props
在这种情况下是未定义的。我已经尝试过了,我无法映射配方。结果就是这样。您使用Redux吗?我认为问题在于如何使用dispatch。您是否将存储连接到组件?调度定义了吗?是的,我正在使用Redux。已定义分派(const dispatch=useDispatch()),并将其连接到存储。单击按钮时是否可以记录toggleFavoriteAction
?错误表明它不是一个函数,这将提示我们它实际上是什么。使用这种方法,我的配方现在未定义。因为您正在传播数据
,因此如果您想这样做,您将无法作为配方
访问它,您可以以任何剩余属性进入配方对象的方式来分解道具,即让{toggleFavoriteAction,favorites,…recipe}=props
答案是可以的,但不要指定数据:
// RecipeListItem
const RecipeListItem = (recipe: RecipeConfig, props: any): JSX.Element => {
const { toggleFavoriteAction, favorites } = props;
...
......
<button onClick={() => toggleFavoriteAction(recipe)}> // this button
{favorites && favorites.find((fav: any) => fav.id === recipe.id)
? 'Remove from fav'
: 'Add to fav'}
</button>
// RecipeListItem
const RecipeListItem = (recipe: RecipeConfig, props: any): JSX.Element => { //here is wrong
const { toggleFavoriteAction, favorites } = props;
...
......
<button onClick={() => toggleFavoriteAction(recipe)}> // this button
{favorites && favorites.find((fav: any) => fav.id === recipe.id)
? 'Remove from fav'
: 'Add to fav'}
</button>
// RecipeListItem
const RecipeListItem = (props: any): JSX.Element => {
const { toggleFavoriteAction, favorites, recipe } = props;
...
......
<button onClick={() => toggleFavoriteAction(recipe)}> // this button
{favorites && favorites.find((fav: any) => fav.id === recipe.id)
? 'Remove from fav'
: 'Add to fav'}
</button>
<RecipeListItem {...data} {...props} />
const RecipeListItem = (props: any): JSX.Element => {
....