使用动态导入时console.log消息在react.js中不一致地记录

时间:2019-01-18 10:20:58

标签: javascript reactjs

嘿,我在通过CRA(create-react-app)创建的我的react应用程序中观察到这种奇怪的行为,其中我尝试记录的控制台日志消息被不一致地记录,有时根本不是这里的我的代码

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Dynamic extends Component {
  constructor(props) {
    super(props);
    this.state = { module: null };
  }
  componentDidMount() {
      console.log('in comp mount')
      alert("in comp mount")
    const { path } = this.props;
    import(`${path}`)
      .then(module => this.setState({ module: module.default }))
 }
  render() {
      console.log('in render')
      alert("in render")
    const { module: Component } = this.state; // Assigning to new variable names @see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
    return(
      <div>
        {Component && <Component />}
      </div>
    )
  }
}

ReactDOM.render(<Dynamic path='./FirstComponent' />, document.getElementById('root'));

请注意,每次敲响警报并在浏览器中显示警报时,控制台消息的记录都非常不一致,并且componentDidMount()函数中的消息根本不会被打印。我用裸露的标准create-react-app项目尝试了同样的事情,它正确显示了消息,所以我猜想它与动态导入有关

1 个答案:

答案 0 :(得分:0)

不要**不要在componentDidMount()中调用setState,这是eslint中的一个皮棉,有关详细信息,请参考this link

  

“反应/未安装数量设置状态”

默认情况下,此规则禁止在函数外部的componentDidMount中对this.setState的任何调用。

以下模式被视为警告:

var Hello = createReactClass({
  componentDidMount: function() {
    this.setState({
      name: this.props.name.toUpperCase()
    });
  },
  render: function() {
    return <div>Hello {this.state.name}</div>;
  }
});

因此,请改用以下代码段模式

var Hello = createReactClass({
  componentDidMount: function() {
    this.onMount(function callback(newName) {
      this.setState({
        name: newName
      });
    });
  },
  render: function() {
    return <div>Hello {this.state.name}</div>;
  }
});