【问题标题】:How fetch data from REST API and populate an array with JSON data in reactjs?如何从 REST API 获取数据并在 reactjs 中使用 JSON 数据填充数组?
【发布时间】:2018-07-01 22:12:31
【问题描述】:

我正在尝试使用来自 REST API 的 JSON 数据填充 matches:[]。我无法从 REST API 获取()数据。

REST API 的 JSON 响应:

在 main.js 中:

import React, { Component } from 'react';

class Main extends Component {
    constructor(props){
        super(props);
        this.state = {
            matches:[]
        };
    }

    componentDidMount(){
        fetch('api/matches')
        .then(res => this.setState({matches}, () => console.log('Matches fetched...', matches)));
    }

    render() {
    return (
      <div>
          <div class="row">
            <div class="col-lg-4" styles="background-color:lavender;">{this.state.matches[0].season}</div>
            <div class="col-lg-4" styles="background-color:lavenderblush;">{this.state.matches[5].season}</div>
            <div class="col-lg-4" styles="background-color:lavender;">{this.state.matches[8].season}</div>
          </div>
      </div>
    );
  }
}

export default Main;

我稍后将 JSON 数据填充到引导程序中以在网格系统中显示它,但我收到错误,这些行显示以下行的 TypeError:

this.state.matches[0].season
this.state.matches[5].season
this.state.matches[8].season

【问题讨论】:

  • 你用 XHR 检查了网络选项卡吗?这个 API 的响应是什么
  • @RIYAJKHAN imgur.com/a/H0Krf

标签: javascript json reactjs rest


【解决方案1】:

访问matches[0]matches[5]matches[8] 而不从您的API 中获取将会破坏您的应用程序。

我建议将render 方法更改为:

render() {
  if (this.state.loading) {
    return <div>Loading...</div>
  }
  if (this.state.matches.length === 0) {
    return <div>There aren't any matches !</div>
  }
  return (
    <div>
      <div class="row">
        <div class="col-lg-4" styles="background-color:lavender;">{this.state.matches[0].season}</div>
        <div class="col-lg-4" styles="background-color:lavenderblush;">{this.state.matches[5].season}</div>
        <div class="col-lg-4" styles="background-color:lavender;">{this.state.matches[8].season}</div>
      </div>
    </div>
  )
}

在你启动fetch之后,你仍然需要将响应解析成你想要的格式(本例中为JSON)。在那之后,你就可以使用setState

state = {
  matches: [],
  loading: true
};
componentDidMount() {
  fetch('/api/matches')
    .then(res => res.json()) // It resolves the promise with a JSON object
    .then(res => {
      console.log(res) // make sure that matches is `res` directly or a neste object within `res` object
      this.setState({
        matches: res,
        loading: false
      })
    })
}

如果您需要更多关于fetch 及其工作原理的信息,我建议您阅读David Walsh's 的解释。

【讨论】:

  • 我得到了未定义的匹配项。
  • @stonerock 在设置状态之前尝试console.log(res) 以检查来自 api 的结果是否存在。
  • 现在我得到 res not defined
  • @stonerock 我刚刚更新了我的答案。希望它现在有帮助:)
  • @stonerock 当然。我建议从 ReactJS 的条件渲染教程开始:reactjs.org/docs/conditional-rendering.html
【解决方案2】:

我可以看到你没有正确调用 api 路由。假设您确实以如下方式设置了 api -

app.get('/api/matches', (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ matches }));
});

我是你的反应代码,你可以调用 api 为 -

fetch('/api/matches).then()

注意/

希望这有帮助吗?否则请告诉我。

【讨论】:

  • 为什么我需要添加这些行 res.setHeader('Content-Type', 'application/json');`` res.send(JSON.stringify({ matches })); 因为它已经将 JSON 数据发送到 REST API 端点 localhost:5000/api/matches
  • 不需要在api/matches中使用/,因为我正在使用代理-> localhost:5000
猜你喜欢
  • 2020-10-05
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多