【发布时间】:2020-07-08 07:30:48
【问题描述】:
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
age: 10,
};
}
handleincrement = () => {
console.log("hy");
this.setState((prevState) => {
return { age: prevState.age + 1 };
});
}
render() {
return (
<div>
<button onClick={this.handleincrement}>
counter value is {this.state.age}
</button>
</div>
);
}
}
function App() {
return (
<div>
<Counter />
<Counter />
</div>
);
}
我有一个组件计数器,当我单击第一个按钮时,我在 App.js 类中使用了 2 次,它导致仅增加第一个计数器组件的状态值,反之亦然。 我的问题是,为什么这两个组件的行为彼此独立?
【问题讨论】:
-
因为计数器组件有自己的状态。两个 Counter Child 组件意味着它们都有独立的实例和状态。
标签: javascript reactjs react-router react-component react-component-unmount