我是一个相对较新的反应,并试图找到适当的方式来处理更改输入复选框的状态。
我有一个真或假的复选框,这取决于数据库中的布尔值。我目前使用defaultChecked在用户加载状态时将复选框设置为true或false。我尝试使用checked,复选框会触发onClick函数并更新数据库,但复选框会保持初始的布尔值状态。
因此,当您单击复选框时,onClick事件将调用一个函数,该函数应将数据库布尔值更新为true或false。我的问题是,如果数据库没有实际更新,我不希望复选框变为true或false。如果更新时出现通信错误,并且response.sucess为false,则复选框应停留在最初加载状态时所使用的值。仅当response.success为true时,该复选框才应切换。对正确的方法有什么建议吗?我相信我只需要更新状态,但对于如何使用复选框和数据库进行更新有点困惑。谢谢。
<input
id="database-boolean"type="
checkbox"defaultChecked={this.props.dataBaseBoolean}
handleUpdate={this.handleUpdateDataBaseBoolean}
onClick={(e) => this.handleUpdateDataBaseBoolean(e)}
/>
handleUpdateDataBaseBoolean = (e) => {
const {key} =this.props;
this.props.updateDataBaseBoolean(key, e).then((response) => {
if(response.success) {
toastr.success(response.message, { timeOut: 2000, position: 'top-center'});
}else{
toastr.error("Failed to update boolean", { timeOut: 2000, position: 'top-center'});
}
}
)};
发布于 2020-12-13 00:48:27
我会将isLoading
添加到状态中,然后禁用加载时的按钮,然后添加条件以检查是否成功。
const [isLoading, setIsLoading] = useState(false);
...
{isLoading ? regular input : loading input}
为简单起见,您可以只将加载输入显示为禁用输入。
https://stackoverflow.com/questions/65271291
复制相似问题