组件中不提供来自第二个提取API的数据

时间:2019-04-29 16:59:19

标签: reactjs fetch-api

我正在尝试渲染一个组件,该组件使用fetch()调用从Django rest框架获取数据。由于数据的结构方式,我必须使用两次提取。

当我在接收到数据并将其传递到组件并进行console.log记录后尝试设置状态时,我得到了空括号{},并且在展开它时我有数据但我无法访问它。但是如果我展开它,我可以看到数据

示例: {} 酒店:123, 办公室:456

data.Hotel =未定义

通常,当我console.log数据时,它看起来像 {Hotel:123,Office:456}

结构化反应是错误的还是我错过了什么? 我是新来的反应者,所以将不胜感激。

DataProvider.js

import React, { Component } from "react";
import PropTypes from "prop-types";
class DataProvider extends Component {
  static propTypes = {
   endpoint: PropTypes.string.isRequired,
 };

  state = {
      project: {},
      run_set: [],
      project_eui: 0,
      run_euis: {},
      loaded: false,
      placeholder: "Loading.."
    };

  componentDidMount() {
  let currentComponent = this;
  var project = {}
  var run_set = {}
  var project_eui = 0
  var run_euis = {}
  var run_sets = []
  try {
    const data = {username: 'username', password: 'password'};
    fetch('URL', {
      method: 'POST',
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    }).then(function(response) {
      return response.json();
    }).then(function(data){
      return data.token
    }).then(function(token){
      try {
        fetch(currentComponent.props.endpoint, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'authorization': 'Token ' + token
          }
        }).then(function(response) {
          return response.json();
        }).then(function(project){
          project = project
          project_eui = project.eui


          var numBuildingType = project.run_set.length
          for (let i = 0; i < numBuildingType; i++) {
            try {
               //URL from 1st fetch call
              fetch(project.run_set[i], {
                method: 'GET',
                headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
                  'authorization': 'Token ' + token
                }
              }).then(function(response) {
                return response.json();
              }).then(function(run_set){
                run_sets.push(run_set)
                run_euis[run_set.building_type] = run_set.eui
              })
            } catch (e) {
              console.log(e);
            }
          }
        })
      } catch (e) {
        console.log(e);
      }
    })
  } catch (e) {
    console.log(e);
  }
  currentComponent.setState({ project: project, project_eui: project_eui, run_set: run_sets, run_euis: run_euis, loaded: true });
}
  render() {
    const { project, project_eui, run_set, run_euis, loaded, placeholder } = this.state
    if (loaded == true) {
      const myJson = { "project": this.state.project, "run_set": this.state.run_set, "project_eui": this.state.project_eui, "run_euis": this.state.run_euis}
      return this.props.render(myJson)
    } else {
      return <p> {placeholder} </p>
    }
  }
}

StructureData.js


...

const StructureData = ({ data }) => {
  console.log(data.run_euis) --------------------> {}
  return (
  <div>
    <p>something</p>
  </div>
);
}

export default StructureData;

App.js

...
return <DataProvider endpoint= {projectApiEndpoint}
                       render= {data => <StructureData data={data} />}
                      />
...

1 个答案:

答案 0 :(得分:1)

currentComponent.setState({ project: project, project_eui: project_eui, run_set: run_sets, run_euis: run_euis, loaded: true });在错误的位置。

您将启动一个非常复杂的异步Promise链,其中涉及fetch。该代码将需要一些时间才能完成。之后,您不能立即同步使用setState,因为您的fetch代码仍在运行中。您的setState通话需要在fetch成功产生的.then内部,也许在这里?

              //URL from 1st fetch call
              fetch(project.run_set[i], {
                method: 'GET',
                headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
                  'authorization': 'Token ' + token
                }
              }).then(function(response) {
                return response.json();
              }).then(function(run_set){
                run_sets.push(run_set)
                run_euis[run_set.building_type] = run_set.eui
                currentComponent.setState({ project: project, project_eui: project_eui, run_set: run_sets, run_euis: run_euis, loaded: true });
              })

您在控制台中看到的行为是由于以下事实:当您将对象记录到控制台时,您看到的是对象被记录时的值。在这种情况下,您将创建一个对象变量,启动一个fetch调用,然后记录该对象-但此时该对象仍为空。但是,当您单击控制台中的“展开”箭头时,它将重新评估该对象并向您显示其新的 current 值-恰好是fetch之后完成。使用console.log进行调试可能会产生诸如此类的怪异行为;我建议您习惯使用调试器工具。 https://medium.freecodecamp.org/mutating-objects-what-will-be-logged-in-the-console-ffb24e241e07