使用Firebase在React JS中进行映射

时间:2018-09-12 14:58:35

标签: javascript reactjs firebase google-cloud-firestore

我有两个集合,分别是“主题”和“用户”,我想将它们映射到同一个箭头函数中,以便能够仅通过一个箭头函数来检索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);

1 个答案:

答案 0 :(得分:0)

如果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>
                      ))}