【问题标题】:In React, how to show data from API in a HTML table?在 React 中,如何在 HTML 表格中显示来自 API 的数据?
【发布时间】:2017-03-07 04:41:09
【问题描述】:

我正在尝试显示来自我的示例 API 的数据。目前我可以遍历数组,并显示所有标题,例如:

EventTitle1
EventTitle2
EventTitle3
...

这是我的代码:

class App extends React.Component {
constructor() {
   super();
   this.state = {
      data: []
   }
}
 
componentDidMount() {
 var th = this;
 this.serverRequest = axios.get(this.props.source)
 .then(function(event) { 
     th.setState({
         data: event.data
     });
 })
}

componentWillUnmount() {
  this.serverRequest.abort();
}
 
render() {
 var titles = []
 this.state.data.forEach(item => {
    titles.push(<h3 className=”events”>{item.title[0].value}</h3> );
 })
 return (
    <div className=”container”>
      <div className=”row”>
         <div className=”col-md-6 col-md-offset-5">
             <h1 className=”title”>All Events</h1>
             {titles} 
         </div>
      </div>
    </div>
  );
 } 
}

ReactDOM.render(
   <App source=”http://localhost:8888/example/api/events" />, 
   document.getElementById(‘container’)
);

如何创建一个 HTML 表格,以便在表格内仅显示来自 API 的五个最新事件标题(以及后来的其他数据)?

例如:

return (
    <table>
      <tr>
        <th>Event title</th>
        <th>Event location</th> 
      </tr>
      <tr>
        <td>First event title {titles[0]} ?? </td> 
        <td>San Fran</td>
      </tr>
      <tr>
        <td>Second event title {titles[1]} ??</td> 
        <td>London</td> 
      </tr>
    </table>
);

【问题讨论】:

  • 事件位置不是来自API?
  • 是的,也来自API

标签: javascript reactjs


【解决方案1】:

创建一个&lt;tr&gt; 的数组并将其添加到表中。

class App extends React.Component {
constructor() {
   super();
   this.state = {
      data: []
   }
}
 
componentDidMount() {
 var th = this;
 this.serverRequest = axios.get(this.props.source)
 .then(function(event) { 
     th.setState({
         data: event.data
     });
 })
}

componentWillUnmount() {
  this.serverRequest.abort();
}
 
render() {
 const contents = this.state.data.forEach(item => {
      // change the title and location key based on your API
      return <tr>
        <td>{item.title}</td> 
        <td>{item.location}</td>
      </tr>
 })
 return (
    <div className="container">
      <div className="row">
         <div className="col-md-6 col-md-offset-5">
             <h1 className="title">All Events</h1>
             <table>
              <tr>
                <th>Event title</th>
                <th>Event location</th> 
              </tr>
                {contents}
            </table>
         </div>
      </div>
    </div>
  );
 } 
}

ReactDOM.render(
   <App source="http://localhost:8888/example/api/events" />, 
   document.getElementById("container")
);

【讨论】:

  • 太好了。如何将其限制为仅显示五个最新的?
  • 在渲染中使用{contents.slice(0,5)} 而不是{contents}
  • @PraneshRavi 最好在映射之前对数组进行切片。
  • 不正确。如果您想要其余的值,则无需再次运行map。您可以使用缓存中的数组并从中拼接。
  • 这行错了!它应该使用“.map”而不是“.forEach”。 forEach 不返回任何内容。 const contents = this.state.data.forEach(item =&gt; {
【解决方案2】:

您可以简单地使用slice 运算符来获取数组的前5 个元素,然后直接使用map

也不需要使用titles数组,直接把sn-p inline放到jsx里面就行了

代码的重要部分是:

<table>
    {data.slice(0,5).map(event => (<tr>
        <td>{event.title}</td>
        <td>{event.location}</td>
    </tr>))}
</table>

这里是完整的例子:

class App extends React.Component {
constructor() {
   super();
   this.state = {
      data: []
   }
}
 
componentDidMount() {
 var th = this;
 this.serverRequest = axios.get(this.props.source)
 .then(function(event) { 
     th.setState({
         data: event.data
     });
 })
}

componentWillUnmount() {
  this.serverRequest.abort();
}
 
render() {
 return (
    <div className=”container”>
      <div className=”row”>
         <div className=”col-md-6 col-md-offset-5">
            <h1 className=”title”>All Events</h1>
            <table>
               <tr>
                  <th>Event title</th>
                  <th>Event location</th> 
               </tr>
               {this.state.data.slice(0,5).map(event => (<tr>
                  <td>{event.title}</td>
                  <td>{event.location}</td>
               </tr>))}
            </table>
         </div>
      </div>
    </div>
  );
 } 
}

ReactDOM.render(
   <App source=”http://localhost:8888/example/api/events" />, 
   document.getElementById(‘container’)
);

【讨论】:

    【解决方案3】:

    我只是不会在上面的例子中这样编码。

    1. 我不会使用将变量设置为this 让我想起了很多人做过的 angularjs 的旧时光var vm = this(用于视图模型的 vm)
    2. 需要使用带有箭头函数的现代 javascript 并使用 map 而不是 forEach

      下面的示例:

      class App extends React.Component {
      
          constructor(props) {
              super(props);
              this.state = {
                 data: []
              }
          }
      
          componentDidMount() {
      
             axios.get(this.props.source)
                 .then((event) => { 
                     this.setState({
                         data: event.data
                     });
             })
          }
      
      
      render() {
           const yourData = this.state.data.map(item => (
           // notice array so no return here , ( ) instead of { } 
          // notice also map instead of forEach creates a closure - map is preferred
          <tr>
              <td>{item.title}</td> 
              <td>{item.location}</td>
          </tr>
      })
      return (
         <div className=”container”>
              <div className=”row”>
                   <div className=”col-md-6 col-md-offset-5">
                       <h1 className=”title”>All Events</h1>
                        <table>
                          <tr>
                             <th>Event title</th>
                              <th>Event location</th> 
                          </tr>
                         {yourData}
                     </table>
                   </div>
                </div>
            </div>
           );
         } 
      }
      
       ReactDOM.render(
         <App source=”http://localhost:8888/example/api/events" />, 
             document.getElementById(‘container’)
       );
      
       // above obviously works and old way of doing things, and that is for a div id of containter
      // I would setup an api to append to and use the componentDidMount() {... }  
      // then -->   export default App; 
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 2019-12-05
      • 2015-11-11
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      相关资源
      最近更新 更多