React&Redux应用事件处理器分发Action未触发Reducer求助
解决Redux中切换城市后商店列表不更新的问题
我看了你的代码,问题主要出在两个核心环节:Reducer未处理SHOP_LIST动作,以及容器组件未将商店状态映射到props中。下面一步步帮你修复:
1. 确保Reducer正确处理SHOP_LIST动作
你没有提供Reducer代码,但这是状态不更新的关键原因。如果你的Reducer没有监听SHOP_LIST类型的action,那么即使调用了shoplist(city),Redux的状态也不会产生变化。
示例Shop Reducer代码
创建一个专门处理商店列表的reducer(比如reducers/shopReducer.js):
// reducers/shopReducer.js const initialState = []; export default function shopReducer(state = initialState, action) { switch (action.type) { case "SHOP_LIST": // 收到SHOP_LIST动作时,用payload更新状态 return action.payload; default: return state; } }
合并根Reducer
确保在根reducer中把shopReducer合并进去(比如reducers/index.js):
// reducers/index.js import { combineReducers } from 'redux'; import cityReducer from './cityReducer'; // 你原来处理城市列表的reducer import shopReducer from './shopReducer'; const rootReducer = combineReducers({ insertion_data: cityReducer, // 对应你原来的城市状态 shops: shopReducer // 新增商店状态的映射key }); export default rootReducer;
2. 更新容器组件的mapStateToProps,传递商店状态到子组件
你的App组件的mapStateToProps只返回了城市数据,没有把商店状态传递给props,导致ShopList组件拿不到更新后的商店列表。修改如下:
const mapStateToProps = state => { console.log("map state to props:" + state.shops); return { data: state.insertion_data, shop_data: state.shops // 新增这一行,把商店状态映射到组件props }; };
这样ShopList组件通过{...this.props}就能拿到shop_data,进而渲染对应的商店列表。
3. 确认ShopList组件正确渲染数据
最后检查你的insertion_shoplist.jsx,确保它正确使用shop_data来渲染列表。比如:
// insertion_shoplist.jsx import React from 'react'; const ShopList = ({ shop_data }) => { return ( <div> <h4>当前城市商店</h4> <ul> {shop_data.map(shop => ( <li key={shop.name}>{shop.name}</li> ))} </ul> </div> ); }; export default ShopList;
验证修复效果
现在当你切换城市时:
findShops触发并调用this.props.shoplist(city)shoplistaction返回对应城市的商店数据- Reducer捕获
SHOP_LIST动作并更新shops状态 mapStateToProps把更新后的shops映射到App组件的shop_datapropsShopList组件接收到新的shop_data并重新渲染
这样就能实现城市切换时商店列表同步更新了。
内容的提问来源于stack exchange,提问作者Rui




