【发布时间】:2020-12-26 23:13:36
【问题描述】:
我有三个输入字段,每当我想更新特定字段而不是所有字段时,我没有修改的字段将在我的 mysql 数据库中返回空字符串 ('')。所以我的问题是让我的用户能够只修改他们需要的字段,而不会弄乱未触及的字段。当前默认值也是数据库中的当前值。我曾经能够修改目标字段,但我不能输入多个字符。这就是我使用 defaultValue 属性的原因。如果有人可以帮助我,我会非常高兴。 示例代码如下:
我的用户界面如下所示:
interface User {
fullName: string,
email: string,
password: string
}
表格看起来像这样:
<form method="put" className="updating_current_user" onSubmit={this.updateCuurentUser.bind(this, userId)}>
<input type="hidden" value={userId}/>
<input
type="text"
defaultValue={fullName}
onChange={(e: any) => this.setState({ user: { ...user, fullName: e.target.value } })}
required
/>
<input
type="email"
defaultValue={email}
onChange={(e: any) => this.setState(
{ user: { ...user, email: e.target.value } })}
/>
<input
type="password"
defaultValue={password}
onChange={(e: any) => this.setState({ user: { ...user, password: e.target.value } })}
required
/>
</form>
对于 PUT 方法,我的快递后端是这样的:
app.put('/users/edit', (req, res) => {
const { fullName, email, password, userId} = req.query
const updateCurrentUser = `update users set fullName = '${fullName}', email = '${email}', password = '${password}' where userId = ${userId}`
con.query(updateCurrentUser, (err, results) =>{
if(err){
res.redirect('/users')
} else{
res.send("Data updated...")
}
})
});
我的mysql数据库看起来:
create table if not exists users(
userId INT NOT NULL auto_increment,
fullName VARCHAR(55),
email VARCHAR(55),
password VARCHAR(55),
PRIMARY KEY(userId)
);
我实际上并没有使用表单中的 onSubmit 函数。我是一个带有常规函数的按钮单击,其中 userId 作为唯一参数以更新数据库。我确实对 POST 做了同样的事情,我没有任何问题。所以这就是我的提交函数的样子:
editUserInfo = (userId:number) => {
const { user } = this.state
fetch(`http://localhost:4000/users/edit?fullName=${user.fullName}&email=${user.email}&password=${user.password}&userId=${userId}`, {
method: 'put',
})
.then(res => res.json())
//this.getusers() to get all currently saved users in database
.then(this.getUsers)
}
我认为这就够了,或者我应该清楚得多!!!
【问题讨论】:
-
请发布完整的相关代码,而不是代码图片
-
我刚刚做了@Jayce444
-
这里不一定看出有什么问题,但是您可以发布表单的完整状态以及您从前端发布的方式吗?我可以看到您在输入时传播了整个用户对象,但没有在状态对象的第一级复制任何其他内容
-
我在 PostMan 中使用了相同的端点并且能够更新所有内容:
http://localhost:4000/users/edit?fullName=${user.fullName}&email=${user.email}&password=${user.password}&userId=${userId} -
我认为您所在州的整个“当前”值与用户对象的关系可能是您出错的地方。因为如果你加载页面,输入一个新的用户名,然后提交它,在 React 中电子邮件和密码最初是空字符串,所以空值将被发布到后端。我认为你不应该复制它们。而且你也没有展示你如何加载这些字段的用户初始值,我假设你是在装载时这样做的?
标签: javascript mysql reactjs typescript