对于呈现两次的同一组件,React 构造函数仅调用一次

Tho*_*jka 5 reactjs

我希望这个切换能够工作,但不知何故,组件的构造函数<A/>仅被调用一次。https://codesandbox.io/s/jvr720mz75

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  state = { toggle: false };
  render() {
    const { toggle } = this.state;
    return (
      <div>
        {toggle ? <A prop={"A"} /> : <A prop={"B"} />}
        <button onClick={() => this.setState({ toggle: !toggle })}>
          toggle
        </button>
      </div>
    );
  }
}

class A extends Component {
  constructor(props) {
    super(props);
    console.log("INIT");
    this.state = { content: props.prop };
  }

  render() {
    const { content } = this.state;
    return <div>{content}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)

我已经找到了解决方法https://codesandbox.io/s/0qmnjow1jw

<div style={{ display: toggle ? "none" : "block" }}>
  <A prop={"A"} />
</div>
<div style={{ display: toggle ? "block" : "none" }}>
  <A prop={"B"} />
</div>
Run Code Online (Sandbox Code Playgroud)

我想了解为什么上面的代码不起作用

Rag*_*arg 3

在 React 中,如果您想多次渲染相同的组件并将它们视为不同的,那么您需要为它们提供唯一的key. 尝试下面的代码。

{toggle ? <A key="A" prop={"A"} /> : <A key="B" prop={"B"} />}
Run Code Online (Sandbox Code Playgroud)