首页 > 解决方案 > 使用firebase在react js中映射

问题描述

我有两个集合,它们是“主题”和“用户”,我想将它们映射到同一个箭头函数中,以便能够在一个箭头函数中检索 user.email、topic.topic 和 topic.date。我想在一个箭头函数中映射到来自 firebase 的不同集合。这是我的代码:

   import React, { Component } from "react";
   import { Link } from "react-router-dom";
   import { compose } from "redux";
   import { connect } from "react-redux";
   import { firestoreConnect } from "react-redux-firebase";
   import PropTypes from "prop-types";
   import Spinner from "../layout/Spinner";

   class Topics extends Component {
     state = {};

     render() {
      const { topics, users } = this.props;

      if ((topics, users)) {
        return (
           <div>
             <div className="row">
               <div className="col-md-6 text-center text-info">
                <h2>
                  <i className="fas fa-comments" /> Micro Bloggin
                 </h2>
               </div>
              </div>
              <table className="table table-striped">
                <thead className="thead-inverse">
                  <tr>
                    <th>User</th>
                    <th>Topic</th>
                    <th>Date</th>
                  </tr>
                 </thead>
                 <tbody>
               <--!here I want to introduce user.email instead of 
                   //topic.Username -->
                  {topics.map(topic => (
                     <tr>
                       <td>{topic.userName}</td>
                       <td>{topic.topic}</td>
                       <td>{topic.date}</td>
                    </tr>
                  ))}
               </tbody>
              </table>
            </div>
          );
        } else {
         return <Spinner />;
         }
       }
    }

     Topics.propTypes = {
     firestore: PropTypes.object.isRequired,
     topics: PropTypes.array,
     users: PropTypes.array
    };
   <--!here I call the two collections -->
   export default compose(
   firestoreConnect([{ collection: "topics" }, { collection: "users" 
   }]),
      connect((state, props) => ({
      topics: state.firestore.ordered.topics,
      users: state.firestore.ordered.users
   }))
   )(Topics);

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


如果该userName值在集合中也可用,users也许你可以尝试这样的事情:

 {topics.map(topic => (
                     <tr>
                       <td>
                        {users.find(user=>user.userName === topic.userName).email}
                        </td>
                        <td>{topic.topic}</td>
                        <td>{topic.date}</td>
                      </tr>
                      ))}

推荐阅读