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

标签 javascript reactjs jsx

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

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>
  );
}
此组件具有内部状态:我在此组件内增加鼠标点击计数器:
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>
    );
  }
}
我希望 SomeComponent 中的“计数”状态变量在两个组件中有两个不同的值,但它们共享状态。这是为什么?
这是 live demo to illustrate my point .

最佳答案

您需要添加key Prop 让 react 知道它的不同实例查看您的 fork 示例
https://stackblitz.com/edit/react-g7a6vr?file=src/App.js
官方文档完美地阐明了这一点:

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

关于javascript - 为什么相同类型的两个组件之间共享状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65654764/

相关文章:

javascript - 我想让vuejs中的图像可点击

javascript - 如果导航到 React Native 中的其他屏幕,如何保留 formik 表单值

javascript - 复选框数量可变限制

javascript - 无法在 JavaScript 中设置 null 的属性 'value'

javascript - 在现有的 React 应用程序中逐步采用 Next.js

javascript - React 中的 Socket.IO 连接导致持续重新加载

javascript - React 和 MobX - 用户离开现有页面时的确认对话框

javascript - HTML 标签到 JSX React Native

javascript - React Native 可重用组件的设置状态问题

javascript - 在 IIFE block 中定义一个变量