我正在尝试学习反应,需要一些帮助来了解财产的状态。
因此,当我在输入框中键入内容时,状态会发生变化,而当我删除所有内容时,状态应回到null。
在键入输入并删除后,btnClicked函数中的第一个if语句不起作用(当我单击按钮时,这些框为空)。
if(this.state.email == null || this.state.password == null || this.state.name == null) 返回;
似乎属性值更改为其他值?
这是我的代码:
从'react'导入React 从'react-router-dom'导入{withRouter}
var url =“ http://localhost:50848/api/Users”;
类注册扩展了React.Component {
constructor(props) {
super(props)
this.state = {
email:null,
password:null,
name:null,
massage:false
}
}
emailChanged = (e) => {
this.setState({
email:e.target.value
})
}
passwordChanged = (e) => {
this.setState({
password:e.target.value
})
}
nameChanged = (e) => {
this.setState({
name:e.target.value
})
}
btnClicked = () => {
let objToSend = {
"Email": this.state.email,
"Password": this.state.password,
"Name": this.state.name
}
if(this.state.email == null ||this.state.password == null ||this.state.name == null )
return;
fetch(url,
{
method: 'POST',
body: JSON.stringify(objToSend),
headers: new Headers({
'Content-Type': 'application/json',
'Accepte': 'application/json'
}),
})
.then((resp) => resp.json())
.then((data) => {
console.log(data)
if (data !== "Could not insert user") {
var user = {
email: data.Email,
password: data.Password,
name: data.Name,
id: data.Id
}
this.props.history.push({
pathname: "/Home",
state: { user: user }
})
}
else {
this.setState({
massage:true
})
}
})
.catch((err) => {
console.log(err)
});
}
render() {
return (
<div style={{ textAlign: 'center', marginTop: '10%' }}>
<h2>Sign up</h2>
<input type="text" placeholder="Email" onChange={this.emailChanged}/> <br />
<input type="text" placeholder="password" onChange={this.passwordChanged}/> <br />
<input type="text" placeholder="Name" onChange={this.nameChanged}/> <br /><br />
<button onClick={this.btnClicked}>sign up</button><br /><br />
<h4>{this.state.massage && "Error"}</h4>
</div>
)
}
}
使用Router(SignUp)导出默认值
谢谢
答案 0 :(得分:-1)
我猜这是因为您让浏览器处理输入值。 尝试更改
<input type="text" placeholder="Email" onChange={this.emailChanged}/> <br />
<input type="text" placeholder="password" onChange={this.passwordChanged}/> <br />
<input type="text" placeholder="Name" onChange={this.nameChanged}/> <br /><br />
收件人
<input type="text" placeholder="Email" onChange={this.emailChanged} value={this.state.email} /> <br />
<input type="text" placeholder="password" onChange={this.passwordChanged} value={this.state.password} /> <br />
<input type="text" placeholder="Name" onChange={this.nameChanged} value={this.state.name} /> <br /><br />
这样,您可以确保输入字段的显示值始终与状态对象中的值相同。
编辑: 啊,我的坏。没有正确阅读问题。