如何在React JS中使用JSON显示表格数据?

5
我有一个类似于这样的JSON数据,
我想使用这个JSON数据,然后在React JS中将数据显示在表格中。
以下是我如何从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;

如何使用ReactJS从URL加载JSON并在表格中显示它?
3个回答

7

一旦组件挂载,您可以使用fetch获取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 代码。


2
这是正确的,但componentDidMount()方法是获取数据的首选生命周期方法。从React 16.3开始,componentWillMount()方法将以UNSAFE_作为前缀,并且很可能会在未来的React版本中被删除。请参阅https://reactjs.org/docs/react-component.html#unsafe_componentwillmount。 - trixn
1
我应该先在我的React应用程序中安装Fetch吗?@Phillip - Ahmad
1
请告诉我 @Phillip。 - Ahmad
@Ahmad 如果你无法使用 fetch,那么你的浏览器不支持它。你应该使用我列出的其中一种替代方案。在我的答案中有两个库的链接。 - Phillip
1
@Ahmad 我加入了一些示例代码,但我不知道为你编写代码是否会对你造成不好的影响。你应该学会查看库文档和API。我建议你查看axios文档,这样你就可以了解正在发生什么 :) - Phillip
显示剩余2条评论

2

1
你能否为我编写完整的代码,因为我是React的新手,不知道在你的答案中应该在哪里写这两行代码。 - Ahmad
1
我使用Redux Store来存储我的对象,因此复制/粘贴我的代码对您没有帮助。 您可以调用一个函数,例如在按钮onPress事件上,并在该函数中添加这些行。(不要忘记在函数关键字之前加上async)。下手动吧,这是学习的最佳方式。 - WaLinke
请在 @WaLinke 中添加示例代码,因为我是 React 的新手,已经四天无法显示数据...如果您能帮助我,我将非常感激... - Ahmad

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接