簡體   English   中英

如何在反應js中使用json在表中顯示數據?

[英]how to display data in table using json in react js?

我有JSON像這樣

我想使用這個JSON並使用react js在Table中顯示數據。

這是我如何顯示JSON文件中的數據。

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

class App extends Component {
  render() {
    return (
        <ul>
        {
          data.map(function(movie){
            return <li>{movie.id} - {movie.title}</li>;
          })
        }
        </ul>
    );
  }
}

export default App;

如何從URL加載JSON並使用reactjs將其顯示在表中?

您可以在組件安裝后獲取 JSON,當您最終解決它時,您可以更新組件的狀態:

import React, { Component } from 'react';


class App extends Component {
  // initially data is empty in state
  state = { data: [] };

  componentDidMount() {
    // when component mounted, start a GET request
    // to specified URL
    fetch(URL_TO_FETCH)
      // when we get a response map the body to json
      .then(response => response.json())
      // and update the state data to said json
      .then(data => this.setState({ data }));
  }


  render() {
    return (
        <ul>
        {
          this.state.data.map(function(movie){
            return <li key={movie.id}>{movie.id} - {movie.title}</li>;
          })
        }
        </ul>
    );
  }
}

export default App;

如果您無法使用fetch ,則可以使用其他庫,例如superagentaxios 或者你甚至可以回歸到' XMLHttpRequest '。

另一方面,在構建組件列表時,每個孩子都有一個唯一的key屬性是很重要的。 我還在代碼中更新了它,假設movie.id

示例axios代碼:

axios.get(URL)
  .then(response => response.data)
  .then(data => this.setState({ data }));

編輯 :正如trixn在回復中寫道, componentDidMount是獲取數據的首選位置。 更新的代碼。

編輯2 :添加了axios代碼。

您可以使用axios發送http請求。

它看起來像這樣:

const response = await axios.get(your_url_here);
const items = response.data.items;

關於await關鍵字: 如何使用await關鍵字反應原生?

這是docs的axios GitHub頁面: https//github.com/axios/axios

希望能幫助到你。

您可以使用固定的Data表來顯示來自json Response的數據。由於數據量巨大且管理傳統表很困難,因此這將是一個更好的選擇。

文檔見

https://github.com/schrodinger/fixed-data-table-2/blob/master/examples/ObjectDataExample.js

此鏈接將幫助您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM