使用React Hooks+Redux Toolkit实现按钮点击dispatch action的问题
问题排查与修复方案
核心问题点
- 重复声明
routeSelectedaction,类型不匹配:你在reducersRoutes.js的slice中已经通过createSlice自动生成了type为routes/routeSelected的action,又在createActionRoutes.js中手动创建了type为routeSelection的同名action,两者标识完全不一致,导致你dispatch的action无法被slice的reducer捕获,自然不会更新state。 - useSelector取值路径错误:你的slice name为
routes,假设store中注册该reducer的key为routes,state的实际结构是state.routes.selected、state.routes.list,你直接写state.list、state.selected无法获取到对应值。 - createSlice语法缺失:你贴出的slice代码中漏写了
reducers字段,结构不合法。 - 按钮key属性不规范:使用
route[index]作为key不稳定,建议用路由唯一标识作为key。
修复后代码
1. reducersRoutes.js
import { createSlice } from "@reduxjs/toolkit"; import { routesApiCallBegan } from "./createActionRoutes"; const slice = createSlice({ name: "routes", initialState: { selected: '', list: [] // 补充存储路由列表的字段 }, // 补全reducers属性 reducers: { // ...你的其他reducer逻辑 routeSelected: (routes, action) => { routes.selected = action.payload; } }, }); export default slice.reducer; // 导出slice自动生成的action,删除createActionRoutes.js中手动声明的routeSelected export const { routeSelected } = slice.actions; const url = ''; export const loadroutes = () => (dispatch) => { return dispatch( routesApiCallBegan({ url, // ...其他请求配置 onSuccess: routeSelected.type, // 如果你是要设置请求成功回调action,用自动生成的type }) ); };
2. components/routes.js
import { useDispatch, useSelector } from "react-redux"; // 从slice文件导入action,不再从createActionRoutes导入 import { loadroutes, routeSelected } from "../store/reducersRoutes"; import { useEffect } from "react"; import Generic from "./generic"; const Routes = () => { const dispatch = useDispatch(); // 修正取值路径,对应slice的name const routes = useSelector((state) => state.routes.list); const selected = useSelector((state) => state.routes.selected); useEffect(() => { dispatch(loadroutes()); }, [dispatch]); const sendRouteSelection = (selection) => { // 可加这行调试确认拿到的选中值是否正确 console.log('选中值:', selection) dispatch(routeSelected(selection)) } return ( <div> <h1>Available Information:</h1> <ul> {routes.map((route) => ( // 修正key为路由唯一标识 <button key={route[0]} className="routeNav" onClick={() => sendRouteSelection(route[0])}>{route[1]}</button> ))} </ul> {selected !== '' ? <Generic /> : <span>Data should go here...</span>} </div> ); }; export default Routes;
3. 确认store配置正确
确保你在store注册reducer时的key和useSelector的路径对应:
import { configureStore } from '@reduxjs/toolkit' import routesReducer from './reducersRoutes' export const store = configureStore({ reducer: { routes: routesReducer // 这里的key对应state.routes的取值路径 }, })
调试建议
安装Redux DevTools浏览器插件,可直接查看每次dispatch的action内容、payload和state变化,快速定位问题。
内容的提问来源于stack exchange,提问作者AliciaW
相关产品推荐
相关产品推荐

