react 细节知识总结

react ajax请求为什么一般放在didmount 里面那。

    因为,如果你直接在componentWillMount里面使用setState,如下代码:

        

import React, { Component } from 'react';
import GrandSon from './GrandSon.js';
export default class TestComponent extends Component {


  state={
    welcome:'hello'
  }


  componentWillMount(){
    this.setState({welcome:'sdfsdfsdfsdfsdfsdfsdf'})
    // setTimeout(()=>{
    //   console.log('will ---before ajax')
    //   this.setState({welcome:'你好'},()=>{console.log('IIIIIIII')});
    // }, 0) 
    console.log(' will mount')
  }


  componentDidMount(){
    setTimeout(()=>{
      console.log('did ---before ajax')
      this.setState({welcome:'ssd'},()=>{console.log('YYYYYYYY')});
    }, 1000)
    console.log(' did mount')
  }


  render() {
    console.log(' rendering...');
    return (
      <div>
        <GrandSon></GrandSon>
        {this.state.welcome}
      </div>
    );
  }
}

他的子组件:

import React, { Component } from 'react';
export default class GrandSon extends Component {

  render() {
    console.log('grandson rendering')
    return (
      <div>sdfsdfsdfs</div>
    );
  }
}

结果:

Download the React DevTools for a better development experience: https://fb.me/react-devtools
App.js:12 father will mount
App.js:20 father rendering...
LifeCircle.js:15  will mount
LifeCircle.js:27  rendering...
GrandSon.js:5 grandson rendering
LifeCircle.js:23  did mount
App.js:16 father did mount

LifeCircle.js:20 did ---before ajax
LifeCircle.js:27  rendering...
GrandSon.js:5 grandson rendering
LifeCircle.js:21 YYYYYYYY
你会发现componentWillMount中setState没有重新渲染dom,也就是没有走render()


如果你setState注释掉,打开下面注释的代码,结果是这样的:

react-dom.development.js:15380 Download the React DevTools for a better development experience: https://fb.me/react-devtools
App.js:12 father will mount
App.js:20 father rendering...
LifeCircle.js:15  will mount
LifeCircle.js:27  rendering...
GrandSon.js:5 grandson rendering
LifeCircle.js:23  did mount
App.js:16 father did mount

LifeCircle.js:12 will ---before ajax
LifeCircle.js:27  rendering...
GrandSon.js:5 grandson rendering
LifeCircle.js:13 IIIIIIII
LifeCircle.js:20 did ---before ajax
LifeCircle.js:27  rendering...
GrandSon.js:5 grandson rendering
LifeCircle.js:21 YYYYYYYY
也就是重新走了render()


为什么要在didmount里面发送异步请求那,是为了要保证 ajax 调用完成后,DOM 已经准备好了。

所以componentWillMount中的异步操作不知道什么时候执行,在执行完componentWillMount后执行render,然后执行子组件componentWillMount,render;如果此时,当前组件componentWillMount中的异步操作执行完成,执行setState,如果setState中的值载子组件之后,那可能不会刷新,有可能回报错,因为dom还没有准备好。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值