Не показывать ничего - PullRequest
       5

Не показывать ничего

0 голосов
/ 06 февраля 2020

Я работаю над своим проектом, я использую реагирование для моего внешнего интерфейса, и когда я беру свой API и у меня консоль API, он возвращает мой массив, но когда я обрабатываю карту и утешаю его, он показывает пустой массив и ничего не вернуть может кто-нибудь помочь мне, что не так с моим кодом

class Rank extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        error: null,
        isLoaded: false,
        Events: [] = []
    };
}

componentDidMount() {
    fetch("http://localhost/Golfer/api/EventApi/rank?id=2")
        .then(Response => Response.json())
        .then(json => console.log('json', json))
        .then(
            (json) => {
                this.setState({
                    isLoaded: true,
                    Events: (json || [])
                });
            })
    //       // Note: it's important to handle errors here
    //       // instead of a catch() block so that we don't swallow
    //       // exceptions from actual bugs in components.
        //   (error) => {
        //     this.setState({
        //       isLoaded: true,
        //       error
        //     });
        //   }

}

render() {
    const { error, isLoaded, Events } = this.state;
    if (error) {
        return <div><Card><CardBody>Error: {error.message}</CardBody></Card></div>;
    } else if (!isLoaded) {
        return <div><Card><CardBody>Loading...</CardBody></Card></div>;
    } else {
        console.log(this.state.Events)
        return (
            <ul>
                {Events.map(Event => (
                    <li key={Event.title}>
                        <Card>{Event.golfer_events.golfer} {Event.golfer_events.score}</Card>
                    </li>
                ))}
            </ul>
        );
    }
}

Ответы [ 2 ]

1 голос
/ 07 февраля 2020

попробуйте код ниже, надеюсь, что вы очистите его

import React from "react";
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/todos/")
      .then(res => res.json())
      .then(re => {
        this.setState({
          events: re
        });
      });
  }

  render() {
    console.log(this.state.events.length);
    return this.state.events.length > 0 ? (
      <div>
        {this.state.events.map(res => {
          return (
            <div key={res.id}>
              <h1>{res.title}</h1>
            </div>
          );
        })}
      </div>
    ) : (
      <div>
        <h1>....Loading</h1>
      </div>
    );
  }
}
export default App;

, а также вы можете использовать здесь коды и ссылки LINK

0 голосов
/ 06 февраля 2020

установите ваше состояние, как показано ниже

   this.state = {
        error: null,
        isLoaded: false,
        Events: []
    };

И, пожалуйста, отладьте и проверьте в componentDidMount this.setState вы получите данные, а также проверьте, this не определено

...