简体   繁体   English

如何在 React 中从 POST API 调用中渲染数据

[英]How to Render Data from a POST API call in React

I'm trying to figure out how to code my current API call so that I can access each field from the API call and render it, then be able to use it across multiple components.我试图弄清楚如何对我当前的 API 调用进行编码,以便我可以访问 API 调用中的每个字段并呈现它,然后能够在多个组件中使用它。 I'm using the QuickBase API call that only allows POST to pull field values.我正在使用 QuickBase API 调用,它只允许 POST 提取字段值。 I've been out of the game for a couple of years and can't figure out how to accurately render these to be able to be used in other components by importing the api.js file.我已经退出游戏几年了,无法通过导入 api.js 文件来弄清楚如何准确地渲染这些以便能够在其他组件中使用。 The project is a React within Electron to pull QuickBase data, and be able to create Line Charts (7 on one page) to show a job cost/hours and the jobs included departments cost/hours.该项目是 Electron 中的 React,用于提取 QuickBase 数据,并能够创建折线图(一页上 7 个)以显示工作成本/小时,工作包括部门成本/小时。 All of my data is in quickbase, I just can't figure out how to get it over to react and able to actually use it!我所有的数据都在 quickbase 中,我只是不知道如何让它做出反应并能够实际使用它!

Here is my API call:这是我的 API 电话:

let headers = {
  'QB-Realm-Hostname': 'XXXXXXXXX.quickbase.com',
  'User-Agent': 'FileService_Integration_V2.1',
  'Authorization': 'QB-USER-TOKEN XXXXXX_XXXXX_XXXXXXXXXXXXXXX',
  'Content-Type': 'application/json'
}
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}

fetch('https://api.quickbase.com/v1/records/query',
  {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(body)
  })
  
.then(res => {
  if (res.ok) {
    return res.json().then(res => console.log(res));
  }

return res.json().then(resBody => Promise.reject({status: res.status, ...resBody}));
})

.catch(err => console.log(err))

Any help would be greatly appreciated as I've been struggling on this for awhile.任何帮助将不胜感激,因为我已经为此苦苦挣扎了一段时间。 Right now I'm able to get all the correct data in the Console.现在我能够在控制台中获取所有正确的数据。 But don't know how to go about rendering it on my application for actual use.但不知道如何在我的应用程序上渲染它以供实际使用。

Thanks!谢谢!

I think you should put your code inside a function and call that function from the component where you need the data, something like我认为您应该将代码放入 function 并从需要数据的组件中调用 function ,例如

import React, { Component } from 'react'

let headers = {
  'QB-Realm-Hostname': 'XXXXXXXXX.quickbase.com',
  'User-Agent': 'FileService_Integration_V2.1',
  'Authorization': 'QB-USER-TOKEN XXXXXX_XXXXX_XXXXXXXXXXXXXXX',
  'Content-Type': 'application/json'
};

class App extends Component {
  state = {
    data: null,
  }

  componentDidMount() {
    this.fetchData();
  }    

  fetchData = () => {    
    let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}

    fetch('https://api.quickbase.com/v1/records/query', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(body)
    }).then(response => {
      if (response.ok) {
        return response.json().then(res => {
          this.setState({
            data: res,
          })
        });
      }

      return response.json().then(resBody => Promise.reject({status: response.status, ...resBody}));
    }).catch(err => console.log(err))
  }

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

    if (data === null) return 'Loading...';

    return (
      <div>
        {/* Do something with data */}
      </div>
    );
  }
}

export default App;

Check the Docs , you can send the JSON in the props of the component to render it.查看Docs ,您可以在组件的 props 中发送 JSON 来渲染它。 You can modify your code following this example.您可以按照此示例修改您的代码。

sandbox 沙盒

import { useEffect, useState } from "react";

async function apiCall() {
  return await new Promise((resolve, reject) => {
    // Api Call
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => resolve(json));
  });
}
const TestApp = () => {
  let [data, setData] = useState({ Text: "Before api call." });

  useEffect(() => {
    (async () => {
      let res = await apiCall();
      res.Text = "After api call.";
      setData(res);
    })();
  }, []);
  return (
    <div>
      UserId: {data.userId} &nbsp; id: {data.id} &nbsp; title: {data.title}{" "}
      &nbsp; completed: {data.completed}
    </div>
  );
};

module.exports = TestApp;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM