为什么react组件在不更改状态的情况下渲染两次?

时间:2020-04-19 15:53:09

标签: reactjs react-component react-lifecycle

首先,我在控制台中为每个生命周期挂钩添加了日志

class CircleA extends Component {
  constructor(props) {
    super(props);

    this.state = {
      name: "Circle",
    };
    console.log("Circle-A constructor");
  }

  static getDerivedStateFromProps(props, state) {
    console.log("Circle-A getDeriveStateFromProps Method");
    return null;
  }

  componentDidMount() {
    console.log("Circle-A componentDidMount Method");
  }

  render() {
    console.log("Circle-A render method");
    return <div>Circle-A</div>;
  }
}

然后,在控制台上,直到componentDidMount的每个方法都被调用了两次,而没有更新状态。

这些是控制台消息

i don't understand why is the constructor being called twice

1 个答案:

答案 0 :(得分:1)

这可能是由于React.StrictMode引起的。 React可以多次调用渲染阶段方法来检测副作用。您可能要检查使用ReactDOM.render的index.js文件或主文件,以检查是否有一个名为React.StrictMode的包装器。

以下是同一文档:https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

希望这会有所帮助!