gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:52:17 25 4
gpt4 key购买 nike

我有一个简单的 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 areremoved. Keys should be given to the elements inside the array to givethe elements a stable identity.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com