[英]Function runs properly when called however always returns undefined
我目前正在使用react和firebase来制作一个注册表单,我被困在通过检查firebase中的用户列表来验证是否使用了用户提供的用户名。 这是我的代码的简化版本:
import React, { Component } from 'react';
import * as firebase from 'firebase';
const userList = []
class SignUpForm extends Component {
constructor() {
super();
/*initialize my state*/
}
//get the user list from the database
componentWillMount() {
const users = database.ref('users')
users.once('child_added', snapshot => {
userList.push(snapshot.val())
})
}
/*functions that get username from input and store into the state*/
validateForm() {
//in this.state, 'username' is the text input that the user entered
const { username } = this.state
//this is the function that checks if the username is already in use
const findUsername = (username) => {
userList.map(user => {
if (user.username === username) {
console.log("test")
return true
}
})
}
//if username has been taken
if (findUsername(username)) {
console.log("found the same username in the database")
}
/*other validation checks*/
}
render() {
return(
<div>
{/*input elements, etc*/}
<button onClick={this.validateForm}
</div>
)
}
}
问题是,当我执行console.log(findUsername(username))
,它在控制台中返回undefined
。 但是,它仍然记录字符串“ test”,并运行该函数中编写的所有内容。 它只是在if
语句内未返回true
。 我已经在代码中进行了许多检查,并且可以确保:
userList
包含我存储在userList
中的每个用户 userList
迭代时, console.log(user.username === username)
返回true render()
函数正常工作 这是我第一次问有关Stack Overflow的问题,对于我的帖子中是否存在歧义或缺乏信息,我深表歉意。
return true
是从传递给userList.map()
的匿名函数返回的,而不是从findUsername函数返回的。 userList.map()
不会传播内部匿名函数的返回值。
如果您想知道userList
数组是否包含某些字符串,对我来说根本不清楚为什么要使用map()
。 在我看来,如果您想要一个布尔值,该值指示数组是否包含字符串,则可以使用contains()代替:
return userList.contains(username)
由于该函数不返回任何内容,因此控制台日志未定义。 您在地图内部返回true,但是findUsername本身不返回任何内容。 要检查用户是否存在,只需执行此操作即可。
const hasUser = userList.find(user => user.username === username);
if(!hasUser) {
//no user present. you can proceed further.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.