React-Redux中dispatch触发action creator但reducer未调用问题
问题修复:dispatch调用后Reducer未触发的解决方法
核心问题分析
未使用绑定dispatch的方法触发action
你在HomeView的按钮点击事件里直接调用了全局的setView函数,这只是创建了一个action对象,但没有把它dispatch到Redux store里。connect已经通过props给HomeView注入了绑定好dispatch的setView方法,你需要调用这个props里的方法才会触发reducer。Reducer初始状态处理不规范
viewReducer的state参数没有设置默认值,且返回逻辑里固定返回HOME_VIEW而非当前state,不符合Redux reducer的纯函数规范,可能导致状态更新异常。
修复后的代码
import React, { Component } from 'react'; import { createStore, combineReducers } from 'redux'; import { Provider, connect } from 'react-redux'; // actions const SET_VIEW = 'SET_VIEW'; const setView = (view) => { console.log(view); return { type: SET_VIEW, view }; }; // views const HOME_VIEW = 'HOME'; const OTHER_VIEW = 'OTHER'; //reducers // 修正:给reducer的state参数添加默认值,确保初始状态正确 const viewReducer = function (state = HOME_VIEW, action) { console.log(JSON.stringify(action)); if (action.type === SET_VIEW) { // 简化判断:直接返回合法的目标视图 if ([HOME_VIEW, OTHER_VIEW].includes(action.view)) { return action.view; } } // 默认返回当前state而非固定值,符合纯函数要求 return state; }; const rootReducer = combineReducers({ view: viewReducer, }); // selectors const getView = (state) => state.view; //store // 修正:无需手动传入initialState,reducer默认值已处理初始状态 const store = createStore(rootReducer); function Main({ view }) { return ( <div style={{ width: '250px', display: 'block', margin: 'auto', borderColor: 'black', borderStyle: 'solid', borderWidth: '1px', }} > {view === HOME_VIEW && <HomeViewConnected />} {view === OTHER_VIEW && <OtherView />} </div> ); } const MainConnected = connect( (state) => ({ view: getView(state), }), null )(Main); // 修正:接收props中绑定了dispatch的setView方法 function HomeView({ setView }) { return ( <div> <button onClick={() => setView(OTHER_VIEW)}>View Other</button> </div> ); } const HomeViewConnected = connect(null, (dispatch) => ({ setView: (value) => dispatch(setView(value)), }))(HomeView); class OtherView extends React.Component { render() { return ( <div> <p>Other</p> </div> ); } } class App extends Component { render() { return ( <Provider store={store}> <MainConnected /> </Provider> ); } } export default App;
关键修复点说明
- HomeView组件:添加
{ setView }props接收,按钮点击时调用props中的方法,确保action被正确dispatch到store。 - viewReducer:给state参数设置默认值,默认返回当前state而非固定值,同时简化视图合法性判断,符合Redux reducer的纯函数要求。
- store创建:移除手动传入的initialState,依赖reducer默认值生成初始状态,保持代码简洁规范。
内容的提问来源于stack exchange,提问作者David Colling
相关产品推荐
相关产品推荐

