简体   繁体   中英

How to render state arrays in React in table

I have a component that makes an api call and fetches data and I have in state 6 arrays and with setState I add the data in the arrays and I would like to display it.

I tried this.state.array1.map etc... and so with each array for all rows but it doesn`t display them correctly and I also tried wrapping them in an object in state and mapping the object but it gives me an error.

Here is the code:

import React from 'react';
import axios from 'axios';




 class ListaMesaje extends React.Component {
 constructor(props){
 super(props);
 this.state = {
 obiect: {
 cif: [],
 data_creare: [],
 detalii: [],
 id: [],
 id_solicitare: [],
 tip: []
 }
 

 }
 }




 render() {

 axios.get(`http://localhost/spv/react-php/src/server.php`)
 .then(res => {
 const persons = res.data;

 for(var i = 0; i < 5; i++) {
  this.setState({cif: [...this.state.cif, persons.mesaje[i].cif]});
  this.setState({data_creare: [...this.state.data_creare, persons.mesaje[i].data_creare]});
  this.setState({detalii: [...this.state.detalii, persons.mesaje[i].detalii]});
  this.setState({id: [...this.state.id, persons.mesaje[i].id]});
  this.setState({id_solicitare: [...this.state.id_solicitare, persons.mesaje[i].id_solicitare]});
  this.setState({tip: [...this.state.tip, persons.mesaje[i].tip]});
  }

  })



   return(
  <div>

  {this.state.obiect.cif(x=>(
   <h3>{x}</h3>
   ))}

  </div>
  );
   }


   }

  export default ListaMesaje

I would appreciate if sombody could help me with an example on how to render the all arrays from the state in a html table.

Thanks a lot

Right now, you make an API call, and while you are waiting, you render. When you have received the data and update the state, it triggers a new render and a new API call. New render, new API call etc.

The API calls shouldn't be done in the render method. Move it to the componentDidMount lifecycle method (or an event handler, depending on the behavior you expect). This way, when the component mounts, it makes an API call, does a render with the initial data, and an other one, when you have received the real data.

And in your render method, simply map() through the array:

return(
    <div>
        {this.state.obiect.cif.map(x => (
            <h3>{x}</h3>
        ))}
    </div>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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