Redux中mapStateToProps失效:props.exams返回undefined
解决React-Redux中mapStateToProps获取exams为undefined的问题
我看了你的代码,问题出在创建Redux Store的方式上——你直接把两个reducer传给了createStore,但这不符合Redux的使用规范,导致examReducer根本没被正确加载到store中,自然拿不到exams数据。
问题根源
Redux的createStore函数第一个参数只能接收单个根reducer,你当前的代码:
import { Provider } from "react-redux"; const store = createStore(loginReducer, examReducer); ReactDOM.render( <Provider store={store}> <Exam /> </Provider>, document.getElementById("root") ); registerServiceWorker();
这里的第二个参数examReducer会被当成store的初始state,而不是第二个reducer。也就是说,你的store只使用了loginReducer,examReducer完全没参与状态管理,所以state.exams必然是undefined。
修正步骤
你需要用Redux提供的combineReducers工具把多个reducer合并成一个根reducer,再传给createStore。
- 首先导入
combineReducers:
import { createStore, combineReducers } from 'redux';
- 合并你的两个reducer(给每个reducer指定的key,就是之后在state中访问该reducer状态的路径):
const rootReducer = combineReducers({ login: loginReducer, // loginReducer管理的状态将通过state.login访问 exam: examReducer // examReducer管理的状态将通过state.exam访问 });
- 使用合并后的根reducer创建store:
const store = createStore(rootReducer);
- 修正
mapStateToProps,因为现在exams在state.exam路径下:
const mapStateToProps = (state) => { return { exams: state.exam.exams } }
额外小建议
另外,React现在已经不推荐使用componentWillMount这个生命周期钩子(React 16.3+已标记为不安全),建议把AJAX请求移到componentDidMount中,逻辑完全一致但更符合最佳实践:
componentDidMount() { const xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = () => { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { const json = JSON.parse(xmlhttp.responseText); this.props.dispatch({ type: "ADD_Exams", data: { json } }); } }; xmlhttp.open("GET", "http://127.0.0.1:8000/getExams/", true); xmlhttp.send(); }
这样修改后,你再打印this.props.exams应该就能拿到正确的数据了。
内容的提问来源于stack exchange,提问作者saim2025
相关产品推荐
相关产品推荐

