获取TypeError:repos.map不是函数

时间:2019-12-16 11:50:52

标签: javascript reactjs react-redux mern

我是通过单击按钮查看用户的个人资料而收到此错误的,因为这是一条公共获取路线,但问题似乎是该人提供了与其帐户关联的错误GitHub用户名,但我尝试创建 if语句 ,以检查用户提供的内容是错误还是正确,但似乎根本不起作用。

下面是错误和其他文件。

TypeError: repos.map is not a function

ProfileGithub.render

C:/Users/User/Desktop/Dead end practice/MERN/client/src/components/profile/ProfileGithub.js:36
  33 | render() {
  34 |   const { repos } = this.state;
  35 |   
> 36 |     const repoItems = repos.map(repo => (
     | ^  37 |      <div key={repo.id} className="card card-body mb-2">
  38 |       <div className="row">
  39 |         <div className="col-md-6">
View compiled
finishClassComponent
C:/Users/User/Desktop/Dead end practice/MERN/client/node_modules/react-dom/cjs/react-dom.development.js:18483
  18480 | } else {
  18481 |   {
  18482 |     setCurrentPhase('render');
> 18483 |     nextChildren = instance.render();
        | ^  18484 | 
  18485 |     if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
  18486 |       instance.render();
View compiled
updateClassComponent
C:/Users/User/Desktop/Dead end practice/MERN/client/node_modules/react-dom/cjs/react-dom.development.js:18438
  18435 |   shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
  18436 | }
  18437 | 
> 18438 | var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
        | ^  18439 | {
  18440 |   var inst = workInProgress.stateNode;
  18441 | 
View compiled

ProfileGithub.js文件

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';

class ProfileGithub extends Component {
  constructor(props) {
    super(props);
    this.state = {
      clientId: 'xxxxxxxxxxxxxx',
      clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      count: 5,
      sort: 'created: asc',
      repos: []
    };
  }

  componentDidMount() {
    const { username } = this.props;
    const { count, sort, clientId, clientSecret } = this.state;

    fetch(
      `https://api.github.com/users/${username}/repos?per_page=${count}&sort=${sort}&client_id=${clientId}&client_secret=${clientSecret}`
    )
      .then(res => res.json())
      .then(data => {
        if (this.refs.myRef) {
          this.setState({ repos: data });
        }
      })
      .catch(err => console.log(err));
  }

  render() {
    const { repos } = this.state;

      const repoItems = repos.map(repo => (
       <div key={repo.id} className="card card-body mb-2">
        <div className="row">
          <div className="col-md-6">
            <h4>
              <Link to={repo.html_url} className="text-info" target="_blank">
                {repo.name}
              </Link>
            </h4>
            <p>{repo.description}</p>
          </div>
          <div className="col-md-6">
            <span className="badge badge-info mr-1">
              Stars: {repo.stargazers_count}
            </span>
            <span className="badge badge-secondary mr-1">
              Watchers: {repo.watchers_count}
            </span>
            <span className="badge badge-success">
              Forks: {repo.forks_count}
            </span>
          </div>
        </div>
      </div>
    ));

    return (
      <div ref="myRef">
        <hr />
        <h3 className="mb-4">Latest Github Repos</h3>
        {repoItems}
      </div>
    );
  }
}

ProfileGithub.propTypes = {
  username: PropTypes.string.isRequired
};

export default ProfileGithub;

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为当数据从请求返回而又不是数组时,使用setState设置该数组会导致错误。

.then(data => {
    if (this.refs.myRef) {
        //                 the data isn't an array
        this.setState({ repos: data });
    }
 })

在致电data之前,请检查setState是什么。它必须是一个数组才能工作。

如果您向github api发送无效请求,您将收到此消息

enter image description here

这是一个对象,这可能就是为什么您会收到错误消息。

您可以检查if(data.message){ /* handle api request error */},使其显示错误,并且不会因该错误而更新repos状态。

AND

您还应该检查repos不是null还是undefined

您应该更改

const repoItems = repos.map(repo => (

收件人

const repoItems = repos && repos.map(repo => (