鍍金池/ 問答/HTML/ 小白初學(xué)react,組件初始化怎么獲取數(shù)據(jù)

小白初學(xué)react,組件初始化怎么獲取數(shù)據(jù)

我現(xiàn)在有一個(gè)menu組件,用來展示菜單欄。
我的想法是這樣的:

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

    // 初始化的時(shí)候設(shè)定默認(rèn)值
    static defaultProps = {
        theme: 'light',
        mode: 'inline'
    }
    // 運(yùn)行時(shí)的類型檢測
    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>
        )
    }


}

我想在構(gòu)造函數(shù)的時(shí)候,通過api獲取到menu的值,然后set到state中,但是發(fā)現(xiàn)menu的值為null.

剛學(xué)習(xí)react,所以不知道正確的方式應(yīng)該是什么。 希望指教

附api


import axios from '../utils/axios'


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


回答
編輯回答
哚蕾咪

constructor里面不適合進(jìn)行網(wǎng)絡(luò)請求,可以在 componentWillMount里面

2017年3月29日 03:39
編輯回答
怣人

有可能是異步了,在menus渲染列表的時(shí)候,對應(yīng)的值還沒有獲取到,嘗試直接

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>
        )
    }
2018年9月2日 01:00