React组件的生命周期详解

React组件挂载时有关的生命周期函数有以下几个:

constructor()
componentWillMount()
render()
componentDidMount()

constructor() 构造函数被调用是在组件准备要挂载的最一开始,此时组件尚未挂载到网页上,一般是在这里设置组件的初始状态this.state({})和初始的参数数据。

componentWillMount() 函数方法的调用在constructor()之后,在render()之前,在这方法里的代码调用setState方法不会触发重渲染,所以它一般不会用来作加载数据之用,它也很少被使用到。

如果在这个函数里面调用setState,本次的render函数可以看到更新后的state,并且只渲染一次。

componentDidMount() 在组件挂载之后调用一次,一般从后台(服务器)获取的数据,都会与组件上要用的数据加载有关,所以都写在componentDidMount()方法里面执行加载。所以所有有副作用的代码都会集中在componentDidMount方法里。

案例:


class NewTable extends Component {
    state = {
        selectedRowKeys: [], // Check here to configure the default column
        jsonData: []
    };
    onSelectChange = (selectedRowKeys) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({selectedRowKeys});
    }

    componentDidMount() {
        this.getJsonData();
    }


    getJsonData = () => {
        const _this = this;
        axios.get("http://localhost:3100/selfJson/news.json")
            .then(function (response) {
                let json = response.data.data;
                _this.setState({jsonData: json});
                console.log(json)
            })
            .catch(function (error) {
                console.log(error);
            })

    }
    render() {}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值