简体   繁体   English

Firebase / React查询用户名

[英]Firebase/React query for the user's name

I'm trying to make my Post component work by getting the name of the user who posted it. 我正在尝试通过获取发布该组件的用户的名称来使Post组件正常工作。 Right now, the way it works is that I login with a user (through Google or using email/password combo) and I get the data of that user as auth.currentUser.displayName or email, uid etc... 现在,它的工作方式是我(通过Google或使用电子邮件/密码组合)与用户登录,并以auth.currentUser.displayName或电子邮件,uid等方式获取该用户的数据...

When I make a post, it takes the user's id which is the uid because that is going to be unique. 当我发表文章时,它会使用用户ID(即uid因为这将是唯一的。

Now, when I'm loading the posts I get the post.name which was originally the user's name (until I changed it to store the uid instead) but now I get the ID of the user.... 现在,当我加载帖子时,我得到了post.name ,它原来是用户名(直到我将其更改为存储uid为止),但是现在我得到了用户的ID。...

So my question is: How can I get the user's name instead of the ID? 所以我的问题是:如何获取用户名而不是ID?

这是我数据库中的结构

As you can see on the picture above, the name in the posts is the ID of the user. 如上图所示,帖子中的名称是用户的ID。 I want to get the username of the user when displaying the posts. 显示帖子时,我想获取username的用户username How can I do that? 我怎样才能做到这一点?

I hope it makes some sense.. 我希望这是有道理的。

Here is my render() code: 这是我的render()代码:

render() {
    const { message, posts, error } = this.state;
    const isInvalid = message === '';

    return (
        <div>
            <form onSubmit={this.onSubmit}>
                <p>
                    Posting as:{' '}
                    {auth.currentUser.displayName || auth.currentUser.email}
                </p>
                <textarea
                    value={message}
                    onChange={event =>
                        this.setState(byPropKey('message', event.target.value))
                    }
                    name="message"
                    placeholder="Message..."
                />
                <button disabled={isInvalid} type="submit">
                    Post
                </button>

                {error && <p>{error.message}</p>}
            </form>

            <div>
                <ul>
                    {posts.map(post => (
                        <li key={post.id}>
                            <h4>{post.message}</h4>
                            <p>posted by: {post.name}</p>
                            {post.name === auth.currentUser.uid ? (
                                <button
                                    type="submit"
                                    onClick={() => {
                                        database.ref(`/posts/${post.id}`).remove();
                                    }}
                                >
                                    Delete Post
                                </button>
                            ) : null}
                        </li>
                    ))}
                </ul>
            </div>
        </div>
    );
}

The way i'm displaying the posts: 我显示帖子的方式:

componentDidMount() {
    const postsRef = database.ref('posts');
    postsRef.on('value', snapshot => {
        let posts = snapshot.val();
        let newState = [];
        for (let post in posts) {
            newState.push({
                id: post,
                name: posts[post].name,
                message: posts[post].message
            });
        }
        this.setState({
            posts: newState
        });
    });
}

and the onSubmit: 和onSubmit:

onSubmit = event => {
    const { message } = this.state;

    db.doCreatePost(auth.currentUser.uid, message)
        .then(() => {
            this.setState({
                message: '',
                error: null
            });
        })
        .catch(error => {
            this.setState(byPropKey('error', error));
        });

    event.preventDefault();
};

You can get the username like this. 您可以这样获得用户名。

firebase.database().ref('/users/' + post.name).once('value').then(function(snapshot) { const username = (snapshot.val() && snapshot.val().username) })

  1. Use 'post.name' as a reference to the user. 使用“ post.name”作为对用户的引用。
  2. Search in the 'users' collection the exact value that match that user id. 在“用户”集合中搜索与该用户ID匹配的确切值。
  3. Get 'username' value from the snapshot. 从快照获取“用户名”值。

Hope it helps! 希望能帮助到你!

You'll need to do a client-side join of the user data. 您需要对用户数据进行客户端联接。 In it's simplest form this can be: 用最简单的形式可以是:

componentDidMount() {
    const postsRef = database.ref('posts');
    const usersRef = database.ref('users');
    postsRef.on('value', snapshot => {
        let posts = snapshot.val();
        let newState = [];
        for (let post in posts) {
          usersRef.child(posts[post].name).once('value').then(function(snapshot) {
            const username = snapshot.val().username;
            newState.push({
                id: post,
                uid: posts[post].name,
                name: username,
                message: posts[post].message
            });
            this.setState({
              posts: newState
            });
          })
        }
    });
}

Note that this code sets the state each time a user name is loaded, so you'll see many updates to the UI. 请注意,此代码会在每次加载用户名时设置状态,因此您会看到UI的许多更新。 If you want to reduce that number, look into Promise.all() to wait for all reads. 如果要减少该数目,请查看Promise.all()以等待所有读取。 You'll also want to keep a cache of users you've already loaded, since right now the code loads a user for each post (even if a single user has many posts). 您还需要保留已加载用户的缓存,因为现在代码会为每个帖子加载一个用户(即使单个用户有很多帖子)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “else”语句在更新 Firebase 用户名时不断触发? - “else” statement keeps triggering upon updating Firebase user's name? 如何在React中存储Firebase用户的uid? - How can I store firebase user's uid in React? 使用React进行Firebase查询 - Firebase query with React Firebase查询顺序(以名称开头) - Firebase Query order by and start at name Firebase使用react redux firebase查询第二级 - Firebase query second level with react redux firebase React Native Firebase 查询快照 - React Native Firebase query snapshot 如何在Firebase数据库中查询反应? - How to query in firebase database in react? 如何使用 javascript 在 firebase 中添加用户的额外信息,例如显示名称? - How to add user's extra information such as display name in firebase using javascript? 如何使用 Firebase signInWithCredentials() 设置用户的显示名称和电子邮件 - How can I set a user's display name and email with Firebase signInWithCredentials() FIREBASE phoneAuth (LinkWithPhoneNumber)。 稍后如何在 Firebase Web 中更改用户的关联电话号码。 ( nodejs, Create-react-app )? - FIREBASE phoneAuth ( LinkWithPhoneNumber ) . How to change a user's linked phone number later in Firebase Web. ( nodejs, Create-react-app )?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM