React-redux中mapDispatchToProps无法正常触发action问题求助
问题修复方案
你代码里一共有3处核心错误导致功能失效,逐一修改即可:
- Recipe组件参数定义错误
函数组件的所有props都在第一个参数位置,你写的({recipe}, props)语法错误,导致props根本拿不到connect注入的redux方法,正确写法是把所有需要的属性都从第一个参数解构。 - action调用时没有传递recipe参数
你定义的addToFavoriteRecipesaction要求传入recipe作为payload,但是你在mapDispatchToProps和调用时都没有传递当前组件的recipe对象,导致payload为空。 - 双导出问题
你同时导出了未连接redux的命名组件export const Recipe和连接后默认组件,父组件导入时请使用默认导入写法import Recipe from './Recipe',不要使用命名导入,否则会拿到未注入redux方法的版本导致点击无反应。
修改后的Recipe组件完整代码:
import React, {useState} from 'react'; import {connect} from 'react-redux'; import { addToFavoriteRecipes } from '../../redux/favoriteRecipes/favoriteRecipesActions'; // 去掉命名导出,所有props从第一个参数解构 const Recipe = ({recipe, addToFavoriteRecipes}) => { const [isOpen, setIsOpen] = useState(false); return ( <div className="col-md-3"> <div className="card bwm-card"> <div className="card-title"> <h2>{recipe.title}</h2> </div> <img className="card-img-top" src={recipe.image} alt={recipe.title} /> <div className="card-subtitle"> <h3> <b>Type: {recipe.type} </b> </h3> <h3> <b>Category: {recipe.category}</b> </h3> <h3> <b>Cooking time: {recipe.cookingTime} minutes</b> </h3> </div> <div>//omitted part: show or hide full recipe depending on the state of isOpen</div> <div> {/* 调用时传入当前recipe */} <input type="submit" onClick={() => addToFavoriteRecipes(recipe)} value="add to favorite recipe" /> </div> </div> </div> ); }; const mapStateToProps = state => { return{ favoriteRecipes: state.favoriteRecipes } } const mapDispatchToProps = dispatch => { return{ // 接收recipe参数传给action addToFavoriteRecipes: (recipe) => dispatch(addToFavoriteRecipes(recipe)) } } export default connect(mapStateToProps, mapDispatchToProps)(Recipe)
额外优化建议:
你当前删除收藏的逻辑用了引用比较item => item !== action.payload,如果后续调用删除接口时传入的是新生成的recipe对象,会导致匹配失败删不掉,建议改成用唯一id匹配:
case REMOVE_FROM_FAVORITE_RECIPES: return { ...state, favoriteRecipes: state.favoriteRecipes.filter(item => item.id !== action.payload.id) }
内容的提问来源于stack exchange,提问作者frankmurphy
相关产品推荐
相关产品推荐

