使用React与Redux时props.actions为undefined的问题求助
解决React-Redux中
this.props.actions为undefined导致logInUser调用失败的问题 我之前也碰到过一模一样的问题——在使用React-Redux搭配Antd开发时,触发handleSubmit()时抛出TypeError: Cannot read property 'logInUser' of undefined,打印this.props.actions发现它是undefined。结合你的场景,这里整理几个最容易遗漏的配置点,帮你快速定位问题:
1. 忘记用connect高阶组件绑定组件与Redux Store
这是最常见的原因!如果你的组件没有通过react-redux提供的connect函数和Redux Store关联,根本无法拿到actions相关的props。你需要在组件文件里做这几步:
- 先导入
connect和你的action creator:import { connect } from 'react-redux'; import { logInUser } from './sessionActions'; - 配置
mapDispatchToProps,把action映射到组件props:
如果你习惯用this.props.actions.logInUser的调用方式,要把action包装在actions对象里:
要是觉得嵌套麻烦,也可以直接映射:const mapDispatchToProps = (dispatch) => ({ actions: { logInUser: (userData) => dispatch(logInUser(userData)) } });
这时直接用const mapDispatchToProps = { logInUser };this.props.logInUser就能调用了。 - 最后导出连接后的组件:
export default connect(null, mapDispatchToProps)(YourLoginComponent);
2. mapDispatchToProps配置错误
如果你已经用了connect,但还是拿不到actions,大概率是mapDispatchToProps的结构不对。比如你只映射了logInUser到props根节点,却还在代码里用this.props.actions.logInUser调用,自然会报错。一定要保证调用方式和映射的结构一致。
3. 根组件没被Provider包裹
所有需要访问Redux Store的组件,都必须在Provider的嵌套范围内。检查你的入口文件,是不是有这样的代码:
import { Provider } from 'react-redux'; import store from './your-store-config-file'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
如果没有,赶紧加上,不然connect函数根本找不到Store。
4. Action Creator未正确导出
别小看这个细节!检查sessionActions.js里的logInUser是不是用export导出的:
export const logInUser = (userData) => ({ type: 'LOG_IN_USER', payload: userData });
要是写成了const logInUser = ...却没导出,组件导入的就是undefined,自然没法调用。
内容的提问来源于stack exchange,提问作者andrea56
相关产品推荐
相关产品推荐

