嘿,我想在函数中传递参数,并使用它选择json解析的子级。有可能吗?
我想使用一个函数(checkMatch)来检查数据库中是否有与输入值匹配的用户名。如果是这种情况,它将返回1,否则返回0。
但是我会使用密码和邮件来完成此操作,因此我需要一个函数,可以重新放置用户的子代(例如:user.username或user.password或user.mail)和输入值。
我的json文件非常简单:
{
"users": [
{
"mail": "u@u.u",
"password": 10000,
"username": "Ugo"
},
{
"mail": "a@a.a",
"password": 10000,
"username": "Alice"
}
]
}
我的代码也是如此:
import React, { Component } from 'react';
import './SignIn.css';
class SignIn extends React.Component {
constructor(props) {
super(props);
this.state = {
valueUsername: '',
valuePassword: '',
users: []
};
this.changeUsername = this.changeUsername.bind(this);
this.changePassword = this.changePassword.bind(this);
this.submitForm = this.submitForm.bind(this);
this.checkMatch = this.checkMatch.bind(this);
}
componentDidMount() {
fetch('http://www.json-generator.com/api/json/get/cpAwmuxaqa?indent=2')
.then(response => response.json())
.then((data) => this.setState({users: data.users}));
}
changeUsername(event) {
this.setState({valueUsername: event.target.value});
let match = this.checkMatch('username', event.target.value); // I don't know by what remplace 'username'
console.log(match);
}
changePassword(event) {
this.setState({valuePassword: event.target.value});
let match = this.checkMatch(this.state.users.password, this.state.valuePassword);
console.log(match);
}
submitForm(event) {
alert('A name was submitted: ' + this.state.valueUsername);
event.preventDefault();
}
checkMatch(elem, value) {
let users = this.state.users;
let valueMatch = 0;
users.forEach((user) => {
if (user.elem === value) // I can't concatenate to obtain 'user.username'. So how can I do that ?
valueMatch = 1;
});
return valueMatch;
}
render() { // the render part isn't important
return (
<form id='SignIn_form' onSubmit={this.submitForm}>
<div id='SignIn_emptyInput'></div>
<input type="text" placeholder="Username" value={this.state.valueUsername} onChange={this.changeUsername} />
<input type="password" placeholder="Password" value={this.state.valuePassword} onChange={this.changePassword} />
<input id='submit' type="submit" value="SIGN IN" />
</form>
);
}
}
export default SignIn;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
感谢您的帮助!
答案 0 :(得分:0)
请考虑以下相同的代码段:
users.forEach((user) => {
if (user[elem] === value) {
valueMatch = 1;
}
});
user.elem 在用户对象中寻找elem
键,而elem
是您的变量。因此,您应该编写 user [elem] 。