我有一个react类组件,该组件在其状态下具有类型为“凭据”的参数对象:
{用户:”,密码:”}。
我也在状态下将新的“凭据”添加到“ credentialList”数组中并输出。当我尝试使用列表中已经存在的用户输入新的“凭据”时,我试图使程序给我一个错误。我给每个“凭证”一个等于用户的键值。不幸的是,这没有用。我在** **中标记了有问题的if语句。感谢任何帮助者。我的代码:
state = {
user: '',
password: '',
clicked: false,
credentialsList: []
}
userChangedHandler = (event) => {
this.setState( { user: event.target.value })
}
passwordChangedHandler = (event) => {
this.setState( { password: event.target.value })
}
userSubmitHandler = () => {
if(this.state.user === '' || this.state.password === ''){
alert('Please enter username and password!');
}
const credential = {user: this.state.user , password: this.state.password};
**if(this.state.credentialsList.length !== 0 && this.state.credentialsList.contains(credential)){
alert('Enter New')
}**
else {
let newList = [...this.state.credentialsList, {user: this.state.user, password: this.state.password }];
this.setState({clicked: true, user: '', password: '', credentialsList: newList})
}
}
formEraseHandler = () => {
if(this.state.credentialsList.length === 0){
alert('The User List is Empty!')
}
else {
let newList = [];
this.setState({ credentialsList: newList, user:'', password:''});
}
}
render() {
return(
<div>
<Form
credentialsList={this.state.credentialsList}
user={this.state.user}
password={this.state.password}
clicked={this.state.clicked}
userChanged={(event) => this.userChangedHandler(event)}
passwordChanged={(event) => this.passwordChangedHandler(event)}
addButtonClicked={this.userSubmitHandler}
resetButtonClicked={this.formEraseHandler}/>
<CredentialsList credentials={this.state.credentialsList}/>
</div>
)
}
}
答案 0 :(得分:1)
没有contains
方法,但是您可以使用some()
这里是一个例子:
const exists = this.state.credentialsList.some(v => (v.user === credential.user && v.password === credential.password));
上面的代码检查credentialsList
数组内的任何对象是否具有与user
对象相同的password
和credential
属性值。如果您不想同时检查这两个属性,则可以修改if条件。
答案 1 :(得分:0)
我认为您正在寻找的方法是includes
这会将整个对象与params中给出的对象进行比较。例如:
const credentials = [{ username: 'foo', password: 'bar' }];
credentials.includes({ username: 'foo, password: 'bar' }); // true
credentials.includes({ username: 'foo, password: 'foobar' }); // false
如果要比较特定的值,则some方法更有用 合适
credentials.some(cred => cred.username === this.state.username); // true