Redux连接组件无法接收store props问题求助
我仔细看了你的代码,很快定位到几个关键问题,咱们一步步来修复:
1. 核心错误:导入了未连接Redux的纯UI组件
这是导致props为空的最直接原因!你的App.js里导入的是纯展示组件presentation/Login,而不是已经通过connect()绑定Redux状态和方法的containers/login.js组件。纯UI组件没有和Redux store建立关联,自然拿不到任何props。
修改App.js的导入语句:
// 替换成容器组件的导入路径 import Login from './containers/login';
2. 修正mapStateToProps的state路径
你采用了ducks架构,假设configureStore.js里通过combineReducers把Login reducer注册到了login这个key下(这是ducks的常规命名方式),那原来的mapStateToProps直接取state.page和state.forms是错误的——这些数据实际存储在state.login命名空间下。
修改containers/login.js的mapStateToProps:
const mapStateToProps = (state) => { return { page: state.login.page, forms: state.login.forms } }
如果你的reducer注册用了其他key(比如Login),就对应改成state.Login.page即可。
3. 修复action type的拼写错误
你的redux/modules/login.js里的action type拼写有误:RECIEVE_FORM应该是RECEIVE_FORM(少了一个字母E)。虽然这不会直接导致props为空,但后续调用fetchPage时,reducer会因为匹配不到正确的action type而无法更新状态,所以必须修正:
// 修正拼写 const RECEIVE_FORM = 'RECEIVE_FORM'; export const receiveForm = (response) => ({ type: RECEIVE_FORM, forms: response.forms }) // 同步修改reducer里的case export default function Login(state = initialState, action){ switch (action.type){ case RECEIVE_FORM: return { ...state, forms: action.forms } default: return state; } }
4. 验证store的中间件与reducer注册
最后确认你的redux/configureStore.js正确配置了必要的中间件和reducer:
import { createStore, applyMiddleware, combineReducers } from 'redux'; import thunk from 'redux-thunk'; // 异步action依赖thunk中间件 import login from './modules/login'; const rootReducer = combineReducers({ login, }); export default function configureStore() { return createStore( rootReducer, applyMiddleware(thunk) ); }
注意:你的fetchPage是异步action creator,必须确保store启用了redux-thunk,否则异步逻辑无法被正确处理。
完成以上修改后重启项目,你的Login组件就能正常获取到Redux的props了,componentDidMount里的console.log(this.props)会显示page、forms和fetchPage方法。
内容的提问来源于stack exchange,提问作者UzumakiDev

