javascript - 如何将状态作为道具传递,稍后将通过点击事件更新(同时保持状态更新)
问题描述
React 我尝试制作一个按钮,该按钮将显示使用反应状态单击它的次数。但我想用很多组件来做到这一点。所以我在父组件中使用 setState 编写了我的状态和更新函数,并希望将状态作为道具传递,但问题是我传递了一次状态,然后在状态更新后(单击按钮时)道具不更新。我看不到按钮被点击了多少次。
class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 2,
};
}
clickCount() {
this.setState((prev) => {
return { count: prev.count + 1 };
})
}
render() {
return (
<div>
<MainContent
handler={this.clickCount} totalCount={this.state.count}/>
</div>
);
}
}
export default App;
解决方案
您似乎错过了将函数绑定到this
class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 2,
};
this.clickCount = this.clickCount.bind(this); // you may have missed this..
}
clickCount() {
this.setState((prev) => {
return { count: prev.count + 1 };
})
}
render() {
return (
<div>
<MainContent handler={this.clickCount} totalCount={this.state.count}/>
</div>
);
}
}
export default App;
推荐阅读
- python - sklearn LinearModel、Ridge 和 Lasso 产生不兼容的输出?
- ansible - 如何使用剧本将远程目录复制到本地主机,目录包含不同的用户文件/文件夹?
- apache-pig - 为什么不能从 UNION 操作生成
- java - 如何从现有图像视图上的可绘制对象中获取图像名称
- linux - Android 平台工具:“正在为 UserX 的会话 2 运行停止作业”,我必须等待 90 秒才能关机
- python - Django 使用通用视图,“POST /''/ HTTP/1.1”405 0,不允许方法(POST)
- xml - 删除满足条件的节点,如果为空则删除父节点
- json - Groovy 从变量创建 Json
- python - PyCharm 不允许输入任何代码问题
- python - 如何将数组(二维列表)分配给 Python 中的 dict?