2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
習(xí)慣最常見(jiàn)的數(shù)組原型方法(如.some())將有助于解決這類問(wèn)題。
export const users = [
{ id: 0, name: 'user1', password: 'asd1' },
{ id: 0, name: 'user2', password: 'asd2' },
{ id: 0, name: 'user3', password: 'asd3' },
];
那么你postDetails需要看起來(lái)像這樣:
import { users } from '...';
// ...
postDetails() {
const isUserValid = users.some(user => {
const username = this.state.userName;
const password = this.state.password;
return user.name === username && user.password === password;
});
this.setState({ message: isUserValid });
};

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
有一個(gè)功能,它首先嘗試找到一個(gè)用戶,然后如果我們找到具有相同名稱的對(duì)象,我們檢查密碼。如果某些內(nèi)容無(wú)效,則該函數(shù)返回 false,否則返回 true
const users =[
{id:1,name:"mahesh",password:"mahesh123"},
{id:2,name:"abc",password:"abc123"}
]
const validation = (login, password) => {
const user = users.find(user => login === user.name) // find the user with same name
if (typeof user !== 'undefined') { // check the user. If we didn't find a object with same name, user will be undefined
return user.password === password // if passwords match it returns true
}
return false
}
console.log(validation('mahesh', 'mahesh123'))
console.log(validation('abc', 'abc123'))
console.log(validation('abc', 'sffh'))
console.log(validation('abdsawec', 'abc123'))
添加回答
舉報(bào)