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还没有准备好。