为什么状态在相同类型的两个组件之间共享?

han*_*ris 3 javascript jsx reactjs

我有一个简单的 React 应用程序,我根据布尔变量的值有条件地渲染同一组件的两个实例:

export default function App() {
  const [showFirst, setShowFirst] = useState(true);
  return (
    <div>
      <button type="button" onClick={() => setShowFirst(show => !show)}>
        Switch between components
      </button>
      {showFirst ? (
        <SomeComponent text="I am the first" />
      ) : (
        <SomeComponent text="I am the second" />
      )}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

这个组件有内部状态:我在这个组件内点击鼠标增加一个计数器:

class SomeComponent extends React.Component {
  state = {
    count: 0
  };
  componentDidMount() {
    console.log("mounted");
  }

  componentWillUnmount() {
    console.log("unmounting");
  }

  render() {
    return (
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          border: "2px solid green",
          padding: 8
        }}
      >
        {this.props.text}
        <button
          onClick={() =>
            this.setState(({ count }) => ({
              count: count + 1
            }))
          }
        >
          increase counter
        </button>
        {this.state.count}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望 SomeComponent 中的“count”状态变量在两个组件中具有两个不同的值,但它们共享状态。这是为什么?

这是一个现场演示来说明我的观点

Roy*_*y.B 6

您需要添加key道具让反应知道它的不同实例看到您的分叉示例

https://stackblitz.com/edit/react-g7a6vr?file=src/App.js

官方文档完美地阐明了这一点:

键帮助 React 识别哪些项目已更改、添加或删除。应该为数组内的元素提供键,以赋予元素一个稳定的身份。