【问题标题】:Why is state shared between two components of the same type?为什么相同类型的两个组件之间共享状态?
【发布时间】:2021-01-10 15:10:50
【问题描述】:

我有一个简单的 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>
  );
}

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

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 中的“count”状态变量在两个组件中具有两个不同的值,但它们共享状态。这是为什么呢?

这是live demo to illustrate my point

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    您需要添加 key 属性以让 react 知道它的另一个实例查看您的分叉示例

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

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

    Keys 帮助 React 识别哪些项目已更改、添加或正在更改 删除。键应该给数组内的元素以给出 元素一个稳定的身份。

    【讨论】:

    • 我想知道为什么在这种情况下 react 没有给出警告,而不是在没有键的情况下渲染列表
    • React 在使用相同的键(无键)渲染 2 个组件时会发出警告!
    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2016-01-25
    • 2021-01-07
    相关资源
    最近更新 更多