Redux-Saga在componentDidMount中获取数据返回undefined问题
解决React组件中Redux异步数据初始undefined的问题
你的问题核心在于Reducer的初始状态中没有定义users字段,所以组件挂载时this.props.users会是undefined,直到Saga完成异步请求并触发GET_NON_ACTIVE_USERS_SUCCESS action后,users才会被添加到Redux状态中。以下是不需要用if判断的解决方案:
1. 给Reducer初始状态添加users空数组
在AdminReducers/index.js的INIT_STATE里添加users: [],这样组件一开始拿到的props.users就是空数组,而不是undefined,Ant Design的Table组件可以正常渲染空状态:
import { SHOW_MESSAGE, HIDE_MESSAGE, GET_NON_ACTIVE_USERS, GET_NON_ACTIVE_USERS_SUCCESS, } from "constants/ActionTypes"; const INIT_STATE = { alertMessage: '', showMessage: false, users: [], // 新增:初始化为空数组 loader: false // 确保初始有loading状态字段 }; export default (state = INIT_STATE, action) => { switch (action.type) { // 新增:处理请求开始的action,设置加载状态 case GET_NON_ACTIVE_USERS: { return { ...state, loader: true }; } case GET_NON_ACTIVE_USERS_SUCCESS:{ return { ...state, users: action.payload, loader: false // 请求完成后关闭加载 }; } case SHOW_MESSAGE: { return { ...state, alertMessage: action.payload, showMessage: true, loader: false }; } case HIDE_MESSAGE: { return { ...state, alertMessage: '', showMessage: false, }; } default: return state; } };
2. 优化组件的loading状态与参数传递
你的组件目前自己维护loading状态,但Redux里已经有loader字段,直接复用更合理;另外,getNonActiveUsers需要page和limit参数,组件挂载时要传入默认值,否则请求可能出错:
import React, {Component} from "react"; import {connect} from "react-redux"; import {Table} from "antd"; import {getNonActiveUsers, hideMessage} from "appRedux/actions/AdminActions/"; const columns = [ { title: 'Name & Surname', dataIndex: 'fullName' }, { title: 'Email', dataIndex: 'email' }, { title: 'Phone', dataIndex: 'phone' }, { title: 'Activation Status', dataIndex: 'user_info.activationStatus' } ]; class ActivateInvestors extends Component { state = { pagination: { current: 1, pageSize: 10 } // 初始化分页参数 }; componentDidMount() { // 传入默认的分页参数 this.props.getNonActiveUsers(this.state.pagination); } handleTableChange = (pagination) => { this.setState({ pagination }); // 分页变化时重新请求数据 this.props.getNonActiveUsers({page: pagination.current, limit: pagination.pageSize}); } render() { // 现在this.props.users始终是数组,不用判断undefined return ( <Table columns={columns} rowKey={record => record._id} dataSource={this.props.users} pagination={this.state.pagination} loading={this.props.loader} // 复用Redux的加载状态 onChange={this.handleTableChange} /> ); } } const mapStateToProps = ({admin}) => { const {loader, alertMessage, showMessage, users} = admin; return {loader, alertMessage, showMessage, users}; }; export default connect(mapStateToProps, { getNonActiveUsers, hideMessage })(ActivateInvestors);
为什么这样有效?
- 初始状态的
users: []保证了组件从一开始就能拿到合法的数组类型,Table组件可以正常渲染空表格,无需额外判断。 - 同步Redux的
loader状态,让组件的加载状态和异步请求的生命周期完全绑定,避免状态不一致。
内容的提问来源于stack exchange,提问作者Mehmetali Saraç
相关产品推荐
相关产品推荐

