最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is state shared between two components of the same type? - Stack Overflow

programmeradmin2浏览0评论

I have simple React app, where I conditionally render two instances of the same ponent based on the value of a boolean variable:

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

This ponent has internal state: I increase a counter on a mouse click inside this ponent:

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

  ponentWillUnmount() {
    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>
    );
  }
}

I expected the 'count' state variable inside SomeComponent to have two different values inside the two ponents, but they share state. Why is that?

Here is a live demo to illustrate my point.

I have simple React app, where I conditionally render two instances of the same ponent based on the value of a boolean variable:

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

This ponent has internal state: I increase a counter on a mouse click inside this ponent:

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

  ponentWillUnmount() {
    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>
    );
  }
}

I expected the 'count' state variable inside SomeComponent to have two different values inside the two ponents, but they share state. Why is that?

Here is a live demo to illustrate my point.

Share Improve this question asked Jan 10, 2021 at 15:10 handrishandris 2,1098 gold badges28 silver badges44 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

You need to add key prop to let react know its a different instance see your forked example

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

The official documentation clarifies this perfectly:

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.

发布评论

评论列表(0)

  1. 暂无评论