简体   繁体   English

如何在 React 中将 JSON 数据渲染为表格

[英]How to display JSON data inside render as table in React

I am using an API which returns JSON of various different key-value pairs.我正在使用一个 API,它返回各种不同键值对的 JSON。 I am trying to display them inside of render() as a table of 2 columns, key and value, with object keys and values in them, respectively.我试图在render()中将它们显示为 2 列、键和值的表,其中分别包含对象键和值。

  1. The API in fetchBasicDetails() is POST which takes default this.state values as input and returns the JSON output. fetchBasicDetails()的 API 是 POST,它以默认的 this.state 值作为输入并返回 JSON 输出。
  2. The JSON Output object is then stored to birth_details property of this.state using setState method.然后使用setState方法将 JSON 输出对象存储到this.state 的birth_details属性。
  3. Then, I tried to show the object data in <table> tags using forEach and Object.keys, which shows nothing at all.然后,我尝试使用forEach和 Object.keys 在<table>标签中显示对象数据,这根本不显示任何内容。

Any help is appreciated.任何帮助表示赞赏。 Thank you.谢谢你。

export default class HoroscopeReport extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      day: 11,
      month: 2,
      year: 2019,
      hours: 12,
      minutes: 59,
      tzone: 5.5,
      lat: 19.22,
      lon: 25.2,
      birth_details:{}
    };
  }

  handleSubmit = event => {
    event.preventDefault();
    //console.log("Received user submitted data"+JSON.stringify(this.state))
    this.fetchBasicDetails();
  };

  fetchBasicDetails() {
        let myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
        myHeaders.append("Authorization", "Basic XXXXXXXXXXXXXXX");

        let urlencoded = new URLSearchParams();
        urlencoded.append("day", this.state.day);
        urlencoded.append("month", this.state.month);
        urlencoded.append("year", this.state.year);
        urlencoded.append("hour", this.state.hours);
        urlencoded.append("min", this.state.minutes);
        urlencoded.append("lat", this.state.lat);
        urlencoded.append("lon", this.state.lon);
        urlencoded.append("tzone", this.state.tzone);

        let requestOptions = {
          method: 'POST',
          headers: myHeaders,
          body: urlencoded,
          redirect: 'follow'
        };

        fetch("https://json.astrologyapi.com/v1/birth_details", requestOptions)
          .then(response => response.text())
          .then(result => {
            this.setState({ birth_details: result });
          })
          .catch(error => console.log('error', error));
       }

  render() {

    return (
      <div>
{/* FORM SUBMITTION CODE HERE */}
              <h2>Output:-</h2>
              <table border={2} cellPadding={5}>
                <thead>
                  <tr>
                    <td>Key</td>
                    <td>Value</td>
                  </tr>
                </thead>
                <tbody>
                  Object.keys(this.birth_details).forEach(function (element) {
                  return <tr><td>element</td><td>this.birth_details[element]</td></tr>;
                  });
                </tbody>
              </table>
      </div>
    );
  }
}

For reference, This is the output of JSON:-作为参考,这是 JSON 的输出:-

{"year":2019,"month":2,"day":11,"hour":12,"minute":59,"latitude":19.22,"longitude":25.2,"timezone":5.5,"gender":" ","name":" ","seconds":0,"ayanamsha":24.124044280610406,"sunrise":"10:19:50","sunset":"21:47:13"}

Usually rendering elements based on an array in React is handled with map() instead of forEach() .通常在 React 中渲染基于数组的元素是使用map()而不是forEach() The reason is with map() you can manipulate each elements meanwhile iteration and return a completely fit JSX syntax for render method.原因是使用map()您可以在迭代的同时操作每个元素并为render方法返回完全适合的JSX语法。 In the same time forEach() does not return anything, only undefined .同时forEach()不返回任何内容,只返回undefined

I guess you can try the following:我想您可以尝试以下操作:

render() {
    return (
      <div>
        <h2>Output:-</h2>
        <table border={2} cellPadding={5}>
           <thead>
              <tr>
                <td>Key</td>
                <td>Value</td>
              </tr>
           </thead>
           <tbody>
              {
                  this.state.birth_details && 
                  Object.keys(this.state.birth_details).map(function (element) {
                     return <tr>
                       <td>{element}</td>
                       <td>{this.state.birth_details[element]}</td>
                     </tr>;
                  });
              }
           </tbody>
        </table>
      </div>
    );
}

I hope that helps!我希望这有帮助!

Remember that you need to use curly braces in JSX to indicate that you want to render the value, not the code as text as-is.请记住,您需要在 JSX 中使用花括号来表示您想要呈现值,而不是按原样呈现代码。

You'll also want to use map instead of forEach .您还需要使用map而不是forEach map is used for transforming an array to something else (we're taking a list of strings and mapping them into React elements), whereas forEach is used to just do something with each element and not return anything. map用于将数组转换为其他内容(我们正在获取字符串列表并将它们映射到 React 元素),而forEach用于仅对每个元素执行某些操作而不返回任何内容。

Additionally, you probably meant this.state.birth_details instead of this.birth_details >此外,您可能指的是this.state.birth_details而不是this.birth_details >

<tbody>
{
  Object.keys(this.state.birth_details).map(function (element) {
    return (
      <tr key={element}>
        <td>{element}</td>
        <td>{this.state.birth_details[element]}</td>
      </tr>
    );
  })
}
</tbody>

I've also set the key on the returned element.我还在返回的元素上设置了key Read more about lists and keys in React here .此处阅读有关 React 中列表和键的更多信息。

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

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