简体   繁体   English

如何将 React API 数据转换为用于其他组件的道具?

[英]How do I convert React API data to props for use in other components?

I've been stuck on this for awhile now and I can't wrap my head around what I need to do with this data to be able to use it in other components.我已经被这个问题困扰了一段时间,我无法理解我需要如何处理这些数据才能在其他组件中使用它。 I'm able to render the data as expected but others tell me to construct the data in a function to be able to call it as props like props.name or props.whatever .我能够按预期呈现数据,但其他人告诉我在 function 中构造数据,以便能够将其称为props.nameprops.whatever之类的道具。 But my issue is also that the API data doesn't classify by text like name, but rather by id's.但我的问题还在于 API 数据不是按名称等文本分类,而是按 id 分类。

{
  "data": [
    {
      "3": {
        "value": 177
      },
      "6": {
        "value": "2220 Three Kings "
      },
      "40": {
        "value": "In Progress"
      },
      "80": {
        "value": 38295.47

So whenever I tried to use this method I get errors.所以每当我尝试使用这种方法时,我都会出错。 I'm also unsure on how to actually change my code to assign each field to it's own prop like title or amount.我也不确定如何实际更改我的代码以将每个字段分配给它自己的道具,例如标题或金额。 I've tried researching all over and haven't had any luck.我已经尝试过全面研究,但没有任何运气。

Here is my API call that is currently rendering data:这是我当前正在渲染数据的 API 调用:

import React, { Component } from 'react'

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

class JobsTableApi extends Component {
  constructor(props) {
    super(props);

    this.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],"where": "{40.CT. 'In Progress'}","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 => response.json())
      .then( data => this.setState({ data })
      );
    }

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

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

    return (
      <ul>
        {Object.keys(data["data"]).map(item => 
          <div key = {item.id}>
            <h2>
              Id: {data["data"][item][3].value} -- {data["data"][item][6].value}
              <br />
              {data["data"][item][40].value}
            </h2>
            <h5>Overall Project Totals:</h5>
              <p>Adj Contract Amount: ${Math.round(data["data"][item][80].value)}</p>
              <p>Design Hours: {Math.round(data["data"][item][88].value)},</p>
              <p>Design Amount: ${Math.round(data["data"][item][91].value)},</p>
              <p>SubRough Hours: {Math.round(data["data"][item][92].value)},</p>
              <p>SubRough Amount: ${Math.round(data["data"][item][95].value)},</p>
              <p>Rough Hours: {Math.round(data["data"][item][96].value)},</p>
              <p>Rough Amount: ${Math.round(data["data"][item][98].value)},</p>
              <p>Finish Hours: {Math.round(data["data"][item][104].value)},</p>
              <p>Finish Amount: ${Math.round(data["data"][item][107].value)},</p>
              <p>Close Hours: {Math.round(data["data"][item][477].value)},</p>
              <p>Close Amount: ${Math.round(data["data"][item][480].value)},</p>
              <p>CURRENT/ACTUAL Hours: {Math.round(data["data"][item][479].value)},</p>
              <p>CURRENT/ACTUAL Amount: ${Math.round(data["data"][item][224].value)}</p>
          </div>
        )}
      </ul>
    )
  }
}

export default JobsTableApi;

Any help or suggestions on How I can use this data, move it over to props with the numeric ID's and be able to call these fields on my other components would be greatly appreciated.任何有关如何使用此数据、将其移至带有数字 ID 的道具以及能够在我的其他组件上调用这些字段的任何帮助或建议将不胜感激。

My idea is that I already have other components that have line charts for areas that I just want to populate with these fields that I'm already getting with this code, I just don't know how to convert to props with Id's and be able to use that in my other components.我的想法是,我已经有其他组件具有折线图,用于我只想用我已经使用此代码获得的这些字段来填充这些区域,我只是不知道如何使用 Id 转换为道具并且能够在我的其他组件中使用它。

UPDATE: I've attempted this multiple times and either get nothing to render, or errors that props or data is undefined.更新:我已经尝试过多次,要么没有渲染,要么道具或数据未定义的错误。 I also console.log(props) and see caller, callee, and arguments properties may not be accessed on strict mode functions or the arguments objects for calls to them.我还 console.log(props) 并查看caller, callee, and arguments properties may not be accessed on strict mode functions or the arguments objects for calls to them. I've moved the API call file directly under src, and my Title.js file where I'm trying to move the data is in src>components>header>Title.js.我已将 API 调用文件直接移动到 src 下,而我试图移动数据的 Title.js 文件位于 src>components>header>Title.js 中。

Title.js:标题.js:

import { React, Component } from 'react'
import '../../JobsTableApi';

class Title extends Component {
  constructor(props) {
    super(props);
    console.log(props)
  }

  render() {
    return (
      <h1>
      {Object.keys(this.props.data["data"]).map(item => 
        <div key = {item.id}>
          <h1>
            {this.props.name}
          </h1>
        </div>
        )
      }
      </h1>
    )
  }
}

export default Title

API Call: API 致电:

import React, { Component } from 'react'
import Title from './components/header/Title.js'

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

class JobsTableApi extends Component {
  constructor(props) {
    super(props);

    this.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],"where": "{40.CT. 'In Progress'}","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 => response.json())
      .then( data => this.setState({ data })
      );
    }

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

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

    return (
      <ul>
        {Object.keys(data["data"]).map(item => 
          <div key = {item.id}>
            <h2>
              <Title name={this.state["data"][item][6].value} /> -- Id: {data["data"][item][3].value} 
              <br />
            {data["data"][item][40].value}
            </h2>
            <h5>Overall Project Totals:</h5>
              <p>Adj Contract Amount: ${Math.round(data["data"][item][80].value)},</p>
              <p>Design Hours: {Math.round(data["data"][item][88].value)},</p>
              <p>Design Amount: ${Math.round(data["data"][item][91].value)},</p>
              <p>SubRough Hours: {Math.round(data["data"][item][92].value)},</p>
              <p>SubRough Amount: ${Math.round(data["data"][item][95].value)},</p>
              <p>Rough Hours: {Math.round(data["data"][item][96].value)},</p>
              <p>Rough Amount: ${Math.round(data["data"][item][98].value)},</p>
              <p>Finish Hours: {Math.round(data["data"][item][104].value)},</p>
              <p>Finish Amount: ${Math.round(data["data"][item][107].value)},</p>
              <p>Close Hours: {Math.round(data["data"][item][477].value)},</p>
              <p>Close Amount: ${Math.round(data["data"][item][480].value)},</p>
              <p>CURRENT/ACTUAL Hours: {Math.round(data["data"][item][479].value)},</p>
              <p>CURRENT/ACTUAL Amount: ${Math.round(data["data"][item][224].value)}</p>
          </div>
        )}
      </ul>
    )
  }
}

export default JobsTableApi;

If I understand this correctly basically you want other components on your project to be able to access the state found within the JobsTableApi class component right?如果我理解正确,基本上你希望项目中的其他组件能够访问在 JobsTableApi class 组件中找到的 state 对吗? Since that state is the one containing the fetched data?既然 state 是包含获取数据的那个? If that is the case then just create the other components as you would eg:如果是这种情况,那么只需像您一样创建其他组件,例如:

class OtherComponent extends Component { constructor(props) {
super(props); } 
}

so then to access the state from other components without triggering a compile error just use the argument props so that everything looks the same as the class component but just with the added props before it for instance this is your code for the JobsTableApi:因此,要从其他组件访问 state 而不会触发编译错误,只需使用参数 props ,以便一切看起来都与 class 组件相同,但只是在它之前添加了 props,例如这是您的 JobsTableApi 代码:

{Object.keys(data["data"]).map(item => 
      <div key = {item.id}>

The access this on new component just use props for instance:对新组件的访问 this 仅使用道具,例如:

{Object.keys(this.props.data["data"]).map(item => 
      <div key = {item.id}>

Then the last step would be to go to your JobsTableApi and import the new component and pass props to it:然后最后一步是将 go 到您的 JobsTableApi 并导入新组件并将道具传递给它:

import OtherComponent from "./OtherComponent";

Then to your render method you could add it to be used around as such:然后到您的渲染方法中,您可以将其添加到周围使用:

render ( return ( <OtherComponent data={this.state.data} /> ) );

Lastly you could also swap this process and instead use your JobsTableApi on the new component you would just need to lift the state to do this or in other words fetch the data on the new component instead.最后,您也可以交换此过程,而是在新组件上使用 JobsTableApi,您只需提升 state 即可执行此操作,或者换句话说,取而代之的是在新组件上获取数据。

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

相关问题 如何执行 function 作为 React 组件之间的道具传递? - How do I execute a function passed as props between components in React? 如何在其他组件 Reactjs 上使用一些道具 - How use some props on other components Reactjs 如何使用道具在组件之间传递数据 - how do i pass data among components using props 如何在 React 风格的组件中使用 this.props - How to use this.props in React Styled Components 反应将道具传递给其他组件 - React passing props to other components React - 获取组件以在道具中使用数据而不是新的 API 请求 - React - Get Components to use data in props rather than new API request 如何添加 1 个 React 组件的 JS state 变量以用于其他组件? - How do I add a JS state variable of 1 React component for use in other components? 如何将历史道具与其他道具一起使用 - How do I use history prop with other props 我正在尝试将 api 中的数据作为我的反应组件中的道具传递,请任何人解释我能做些什么来解决这个问题? - I am trying to pass the data from an api as props in my react components please can anyone explain what i can do to solve the problem? 如何使用React和Axios将this.data传递给其他组件 - How do I pass this.data through to other components with React and Axios
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM