控制台.log使用动态导入时,消息在 React 中记录不一致.js



大家好,我在通过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() 函数中的消息根本没有打印。 我在裸露的标准创建-反应-应用程序项目中尝试了同样的事情,它正确显示消息,所以我猜它与动态导入有关

不要在 componentDidMount() 中调用 setState,这是 eslint 中的 lint,有关详细信息,请参阅此链接。

"反应/无安装设置状态"

默认情况下,此规则禁止在函数之外对 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>;
  }
});

最新更新