无法通过从外部API获取数据来更新状态

时间:2018-05-10 18:53:53

标签: reactjs react-router

我正在制作一个小应用程序,我从外部github API获取数据并更新状态,但是我收到的错误是无法读取null的属性。我创建了两个文件,其中api.js从外部github API获取数据,如代码所示。和Results.js文件相应地更新状态。下面我附上了错误的截图。任何人都可以帮我识别我的代码中的问题。

code ::

api.js

import axios from 'axios';

var id = "YOUR_CLIENT_ID";
var sec = "YOUR_SECRET_ID";
var params = "?client_id=" + id + "&client_secret=" + sec;

function getProfile (username) {
  return axios.get('https://api.github.com/users/' + username + params)
    .then(function (user) {
      return user.data;
    });
}

function getRepos (username) {
  return axios.get('https://api.github.com/users/' + username + '/repos' + params + '&per_page=100');
}

function getStarCount (repos) {
  return repos.data.reduce(function (count, repo) {
    return count + repo.stargazers_count
  }, 0);
}

function calculateScore (profile, repos) {
  var followers = profile.followers;
  var totalStars = getStarCount(repos);

  return (followers * 3) + totalStars;
}

function handleError (error) {
  console.warn(error);
  return null;
}

function getUserData (player) {
  return axios.all([
    getProfile(player),
    getRepos(player)
  ]).then(function (data) {
    var profile = data[0];
    var repos = data[1];

    return {
      profile: profile,
      score: calculateScore(profile, repos)
    }
  });
}

function sortPlayers (players) {
  return players.sort(function (a,b) {
    return b.score - a.score;
  });
}

export default {
  battle: function (players) {
    return axios.all(players.map(getUserData))
      .then(sortPlayers)
      .catch(handleError);
  },

  fetchPopularRepos: function (language) {
    var encodedURI = window.encodeURI('https://api.github.com/search/repositories?q=stars:>1+language:'+ language + '&sort=stars&order=desc&type=Repositories');

    return axios.get(encodedURI)
      .then(function (response) {
        return response.data.items;
      });
  }
};

Results.js

import React from 'react';
import queryString from 'query-string';
import api from '../utils/api';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';

function Player (props) {
   return (
      <div>
         <h1 className='header'> {props.label} </h1>
         <h3 style={{textAlign: 'center'}}> Score: {props.score} </h3>
      </div>
   )
}

Player.propTypes = {
   label: PropTypes.string.isRequired,
   score: PropTypes.number.isRequired,
   profile: PropTypes.object.isRequired
}

class Results extends React.Component {
   constructor(props) {
      super(props);

      this.state = {
         winner: null,
         loser: null,
         error: null,
         loading: true
      }
   }

   componentDidMount() {
    var players = queryString.parse(this.props.location.search);

    api.battle([
      players.playerOneName,
      players.playerTwoName
    ]).then(function (players){
      if (players === null) {
        return this.setState(function () {
          return {
            error: 'Looks like there was an error. Check that both users exist on Github.',
            loading: false,
          }
        });
      }

      this.setState(function () {
        return {
          error: null,
          winner: players[0],
          loser: players[1],
          loading: false,
        }
      });
    }.bind(this));
   }

   render () {
      var error = this.state.error;
      var winner = this.state.winner;
      var loser = this.state.loser;
      var loading = this.state.loading;

      if(loading === true){
         <p> Loading !! </p>
      }

      if (error) {
        return (
          <div>
            <p>{error}</p>
            <Link to='/battle'>Reset</Link>
          </div>
        )
      }

      return (
        <div className='row'>
          <Player
            label='Winner'
            score={winner.score}
            profile={winner.profile}
          />
          <Player
            label='Loser'
            score={loser.score}
            profile={loser.profile}
          />
        </div>
      )
    }
}

export default Results;

错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

在获取完成之前,

this.state.winner为空,这会触发错误。

最初将其设置为{},以便尝试访问它的属性不会导致错误:

this.state = {
  winner: {},
  // insert other states
}