Xiaobai is beginning to learn how to get data from react, component initialization.

I now have a menu component that displays the menu bar.
my idea is this:

import * as React from "react"
import {Menu, Icon} from "antd"
import {getMenuInfo} from "../../api/menu";
import * as PropTypes from "prop-types";

/**
 * state
 *
 * @interface IState
 */
interface IState {
    menus: any[]
}


interface IProps {
    theme?: any
    mode?: any
}

export default class SideMenu extends React.Component<IProps, IState> {
    static state: IState

    // 
    static defaultProps = {
        theme: "light",
        mode: "inline"
    }
    // 
    static propTypes = {
        theme: PropTypes.string,
        mode: PropTypes.string,
    }

    constructor(props: IProps) {
        super(props)
        this.getMenu()
    }

    // state
    getMenu = async () => {
        const data = await getMenuInfo()
        const menus = data.result
        this.setState({
            menus
        })
    }

    render() {
        const menus = this.state.menus
        const menuList = menus.map(item =>
            <Menu.Item key={item.id}>
                <Icon type={item.icon}/>
                <span>{item.name}</span>
            </Menu.Item>
        )
        const {theme, mode} = this.props
        return (
            <div>
                <Menu theme={theme} mode={mode}>
                    {menuList}
                </Menu>
            </div>
        )
    }


}

I want to get the value of menu through api when I construct the function, and then set it to state, but I find that the value of menu is null.

I just learned react, so I don"t know what the right way should be. Hope to give advice

attached API


import axios from "../utils/axios"


export const getMenuInfo = ():any => {
    return axios("/menus/tree")
}


Mar.20,2021

constructor is not suitable for network requests. You can use


in componentWillMount.

may be asynchronous. When menus renders the list, the corresponding value has not yet been obtained. Try to directly

.
render() {
        const {theme, mode} = this.props
        return (
            <div>
                <Menu theme={theme} mode={mode}>
                    {
                        this.state.menus.map(item =>
                            <Menu.Item key={item.id}>
                                <Icon type={item.icon}/>
                                <span>{item.name}</span>
                            </Menu.Item>
                        )
                    }
                </Menu>
            </div>
        )
    }
Menu