首页 > 解决方案 > 如何修改此代码以使渲染等待 Promise Items?

问题描述

我是 React 的新手,我最初在页面加载时从我的数据库中加载所有数据,但是我需要在数组中找到一些信息,而且显然它不是即时的。我需要做些什么来确保渲染方法仅在对象承诺已解决时渲染对象?

我没有尝试太多......我真的被困在这里。

这似乎与我在这里读到的其他问题不同,因为我一开始就加载了一堆信息很好,但是每次调用函数时我都需要调用一些团队信息,所以它不像加载一次那么简单,因为我需要的对象总是不同的。

这段代码是主要问题。我还包括下面的完整文件:

我在编辑中对代码进行了一些修改:我意识到我只需要调用对手球队,因为我已经有了球员球队。

 if (team.id === game.team_1) {
    var redTeam = team;

    // set blueTeam based on game.team_1
    // firebase.teams().doc('teams/{game.team_2}')
  } else {
    var blueTeam = team;

    // set redTeam based on game.team_1
    // firebase.teams().doc('teams/{game.team_1}')

  }

完整文件:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Async from 'react-promise'

import { withFirebase } from '../Firebase';
// import * as ROUTES from '../../constants/routes';

import { Container, Image, Spinner, Col, Row, Card, Accordion, Button } from 'react-bootstrap'

class PlayerGameList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loadingTeams: false,
      loadingSchedule: false,
      teams: [],
      schedule: []
    };
  }

  componentDidMount() {
    this.setState({
      loadingTeams: true,
      loadingSchedule: true,
    });

    this.unsubscribe = this.props.firebase
      .teams()
      .where('players', 'array-contains', '-LXkkB7GNvYrU4UkUMle')
      .onSnapshot(snapshot => {
        let teams = [];

        snapshot.forEach(doc =>
          teams.push({ ...doc.data(), uid: doc.id }),
        );

        this.setState({
          teams,
          loadingTeams: false,
        });
      });

    this.unsubscribe2 = this.props.firebase
      .schedule()
      .onSnapshot(snap => {
        let schedule = [];

        snap.forEach(doc =>
          schedule.push({ ...doc.data(), uid: doc.id }),
        );

        this.setState({
          schedule,
          loadingSchedule: false,
        });
      });
  }

  componentWillUnmount() {
    this.unsubscribe();
    this.unsubscribe2();
  }

  render() {
    const { teams, schedule, loadingTeams, loadingSchedule } = this.state;

    return (
      <div>
        <h2>Games</h2>
        {loadingTeams && loadingSchedule && <div colSpan="12"><Spinner animation="border" role="status">
          <span className="sr-only">Loading...</span>
        </Spinner></div>}

        {/* CONTENT */}
        <Container fluid>
          <Row>
            {getTeams({ teams, schedule })}
          </Row>
        </Container>
      </div >
    );
  }
}

function getTeams({ teams, schedule }) {

  if (!teams) {
    return null;
  }

  if (!teams.length) {
    return null;
  } else {
    return teams.map(team => getGames({ team, schedule }))
  }
}

function getGames({ team, schedule }) {
  schedule.sort((a, b) => (a.time > b.time) ? -1 : 1)

  if (!schedule) {
    return null;
  }

  if (!schedule.length) {
    return null;
  } else {
    return schedule.map(game => guts({ team, game }));
  }
}

function guts({ team, game }) {
  const image = {
    height: '25px',
    width: '25px'
  }

  if (team.id === game.team_1) {
    var redTeam = team;

    // set blueTeam based on game.team_1
    // firebase.teams().doc('teams/{game.team_2}')
  } else {
    var blueTeam = team;

    // set redTeam based on game.team_1
    // firebase.teams().doc('teams/{game.team_1}')

  }


  if (game.team_1 === team.id || game.team_2 === team.id) {
    var time = new Date(game.time.seconds * 1000);
    var dateFormat = require('dateformat');
    var finalTime = dateFormat(time, 'ddd mmm dd, h:MM tt')

    return (
      <Col lg='4' md='6' sm='12' key={game.uid} style={{ marginBottom: '15px' }}>
        <Card>
          <Card.Body>
            <Row>
              <Image src={team.logo} style={image} roundedCircle />
              <p>{team.name}</p>
              <div style={{ height: '25px', width: '25px', backgroundColor: 'red' }}></div>
            </Row>
            <Row>
              <Image src={team.logo} style={image} roundedCircle />
              <p>{team.name}</p>
              <div style={{ height: '25px', width: '25px', backgroundColor: 'blue' }}></div>
            </Row>
            <Row>
              <div>
                {finalTime}
              </div>
            </Row>
          </Card.Body>
          <Accordion>
            <Card style={{ margin: '0', padding: '0' }}>
              <Card.Header>
                <Accordion.Toggle as={Button} variant="link" eventKey="0">
                  Show Match IDs
                  </Accordion.Toggle>
              </Card.Header>
              <Accordion.Collapse eventKey="0">
                <Card.Body>{game.match_id}</Card.Body>
              </Accordion.Collapse>
            </Card>
          </Accordion>
        </Card>
      </Col>
    );
  }
}

export default withFirebase(PlayerGameList);

这些项目都加载为空白,然后几秒钟后,所有控制台日志都与数组对象一起出现。当我告诉它等待程序时,它只会抛出一个错误。

标签: node.jsreactjs

解决方案


推荐阅读