You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件获取MongoDB群组数据始终返回undefined求助

问题情况

开发React应用时,尝试从MongoDB数据库获取所有群组数据,服务器端能正常打印查询到的groups数据,但组件中的groups始终返回undefined,核心问题出在异步操作和Promise的使用上。

服务器端代码(可正常打印groups)

router.get('/groups', async (req, res) => {
    try {
        const groups = await Group.find().sort({ date: -1 });
        res.json(groups);
        console.log(groups);

    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error');
    }
});

Redux Action代码(无法正确获取groups)

export const getAllGroups = () => async (dispatch) => {
  axios
    .get("/api/group/groups")
    .then(res =>
      dispatch({
        type: GET_GROUPS,
        payload: res.payload.data
      })
    )
    .catch(err =>
      dispatch({
        type: GET_GROUPS,
        payload: null
      })
   );
};

React组件代码(groups始终为undefined)

class GroupList extends Component {
   
    componentDidMount() => {
       
        const {groups} = await this.props.getAllGroups();
        this.props.getAllGroups(groups)
    }


    // Delete account
    onDeleteClick = id => {
        const { groups } = this.props;
        const groupData = {
            id: id,
            groups: groups
        };
        this.props.deleteGroup(groupData);
    };


    render() {
        const { user, groups } = this.props;
       
                 let groupItems = groups.map(group => (
                     <li key={group._id} style={{ marginTop: "1rem" }}>
                        <button
                            style={{ marginRight: "1rem" }}
                             onClick={this.onDeleteClick.bind(this, group._id)}
                             className="btn btn-small btn-floating waves-effect waves-light hoverable red accent-3"
                        >
                             <i className="material-icons">delete</i>
                         </button>
                         <b>{group.name}</b>
                     </li>
                ));
        
        return (
            <div>
                <Link to="/" className="btn-flat waves-effect">
                    <i className="material-icons left">keyboard_backspace</i> Back to
                    home
                </Link>
                { { <ul>{groupItems}</ul> } }
            </div>
        )

    }
}

GroupList.propTypes = {
    logoutUser: PropTypes.func.isRequired,
    getAllGroups: PropTypes.func.isRequired,
    deleteGroup: PropTypes.func.isRequired,
    groups: PropTypes.array.isRequired,
    user: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    groups: state.groups
});

export default connect(
    mapStateToProps,
    { getAllGroups, deleteGroup }
)(GroupList);

错误修正点

  • Redux Action数据获取错误:axios请求返回的响应数据在res.data中,不是res.payload.data,需将dispatch的payload改为res.data
  • componentDidMount写法错误:类组件的生命周期方法不能用箭头函数定义;且getAllGroups是Redux action creator,调用后不会直接返回groups数据,无需await,直接调用this.props.getAllGroups()即可,不需要传入参数
  • render方法多余大括号:返回的JSX中{ { <ul>{groupItems}</ul> } }多了一层大括号,应改为{ <ul>{groupItems}</ul> }或直接<ul>{groupItems}</ul>
  • groups空值处理:组件渲染时groups可能还未获取到,需先判断groups是否存在再调用map方法,避免报错,比如let groupItems = groups ? groups.map(...) : null

内容的提问来源于stack exchange,提问作者e.L Creme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 03:25:29