【问题标题】:Which one is called first? constructor or componentDidMount or Render哪个是第一个被调用的?构造函数或 componentDidMount 或 Render
【发布时间】: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-&gt;constructor-&gt;render那样记录
  • 它并没有乱序调用它们。 js 控制台日志中的对象视图是对象的实时视图。这意味着当脚本更改该对象时,控制台将更新该视图以反映这些更改。而且由于这些调用在您查看日志时需要几毫秒才能执行,因此它已经更新,因为到那时 didmount 已经运行并更新了实例
  • 换句话说,对象的控制台日志不是该对象在特定时间的静态视图。
  • 谢谢。对不起,我仍然很困惑,我才刚刚开始使用 react 和 node。

标签: javascript reactjs ecmascript-6 babeljs


【解决方案1】:

我尝试了一些东西,发现效果很好。

window.cnj = require('circular-json') /* 我在起点第一行添加了这个,所以我可以在所有导入中访问它。 */

window.props = JSON.parse(window.cnj.stringify(simple));

我可以从 devtools 访问 window.props 并且它按预期工作。

sample 可以是字符串、数组、普通对象或圆形对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2020-05-06
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多