【发布时间】:2017-12-07 03:43:48
【问题描述】:
正如我已阅读在线和官方文档一样。订单是 Constructor-> ComponentWillMount -> Render -> ComponentDidMount 等。
class Navigation extends Component {
constructor(props) {
super(props);
console.log('constructor', this);
this.state = { items: [ ] };
}
componentDidMount() {
console.log('componentDidMount');
if ( toDisplay( ) ) {
api.bringCats()
.then( categories => {
const tot_cat = categories.map( cat => { return {name: cat.name, link: cat.link}; })
this.setState({items: tot_cat,})
})
}
}
render() {
console.log("render")
//some stuff
}
}
我希望日志按此顺序排列 1.构造函数 2.ComponentDidMount 3. 渲染
我在构造函数方法中使用constructor 记录this。我能够获得items 的价值,它在componentDidMount 中获得价值,为什么会这样?并且它的日志记录顺序正确(构造函数->didmount->render),但是为什么我在调用componentDidMount 之前就获得了items 的值。
我在<Header/> 中使用<Navigation/> 组件
Header extends Component{
render(){
return (<div> <Navigation/> </div>);
}
}
【问题讨论】:
-
因为当您查看构造函数的日志时,脚本已经有时间运行并填充实例对象
-
怎么样?我的意思是,如果它首先进入 ComponentDidMount(),它应该记录
componentdidmount并填充对象对吗?但其记录的顺序是正确的。根据文档。它不像didmount->constructor->render那样记录 -
它并没有乱序调用它们。 js 控制台日志中的对象视图是对象的实时视图。这意味着当脚本更改该对象时,控制台将更新该视图以反映这些更改。而且由于这些调用在您查看日志时需要几毫秒才能执行,因此它已经更新,因为到那时 didmount 已经运行并更新了实例
-
换句话说,对象的控制台日志不是该对象在特定时间的静态视图。
-
谢谢。对不起,我仍然很困惑,我才刚刚开始使用 react 和 node。
标签: javascript reactjs ecmascript-6 babeljs