不显示任何内容

时间:2020-02-06 07:49:54

标签: reactjs rest

我正在我的项目上,我在前端使用react,当我获取我的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 个答案:

答案 0 :(得分:0)

将您的状态设置为以下

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

然后调试并检入componentDidMount this.setState,以接收数据,并检查 this 是否未定义

答案 1 :(得分:0)

尝试以下代码,希望您能清除它

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

使用codeandbox链接