In React, how to show data from API in a HTML tabl

2020-07-24 03:31发布

I'm trying to display data from my example API. At the moment I'm able to loop through the array, and display all the titles, for example:

EventTitle1
EventTitle2
EventTitle3
...

Here is my code:

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’)
);

How could I create an HTML table, to display only the five latest event titles from the API (and later other data) inside the table?

For example:

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>
);

3条回答
乱世女痞
2楼-- · 2020-07-24 03:47

I just would not code it in the above examples like that.

  1. I would not use setting variables to this reminds me the old days of angularjs which a lot of people did var vm = this (vm for view model )
  2. Need to be using modern javascript with arrow functions and use map and not forEach

    sample below:

    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; 
    
查看更多
冷血范
3楼-- · 2020-07-24 03:49

You can simply use the slice operator to get the first 5 elements of you array, and then directly use map.

There is also no need to use a titles array, you can just put the snippet inline in the jsx.

The important part of the code is:

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

Here is the full example:

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’)
);

查看更多
爷的心禁止访问
4楼-- · 2020-07-24 04:08

Create an array of <tr> and add it into the 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() {
 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")
);

查看更多
登录 后发表回答