显示提取数据和渲染-React JS

时间:2019-06-28 06:45:32

标签: javascript reactjs

我能够将数据保存到数据库中。但是,我想知道在运行获取请求后如何在屏幕上显示/渲染获取数据。

当我添加数据时,我可以将其推送到页面上。但是我想要的是,一旦我运行获取数据功能,如何呈现在屏幕上的响应?

当我console.log(json.data.shipping)

时,获取后的Json数据如下所示:
0: { name: "Samsung A10", phone: "001-2342-23429"}
1: {name: "Iphone Xs", phone: "001-12193-1219"}

PS:React JS入门

以下是我如何保存数据

state = {
      shippings: userData,
      addNewData: {
         name: '',
         phone: ''
      },
   };



addData() {
      const { name,phone} = this.state.addNewData;
      if (name!== '' && phone = "") {
         let newData = {
            ...this.state.addNewData,
            id: new Date().getTime()
         }
         let shippings = this.state.shippings;

      fetch( 'http://facicla:5000/api', {
      method:'post',
      /* headers are important*/
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'       
        body: JSON.stringify(this.state.addNewData)
  })
  .then(response => {
     return response.json();
     shippings.push(newData);
     NotificationManager.success('Sucess!');
  })    
      }
   }

userData

 export default [
        {
            name: 'Shipping-Car',
            phone: '001-72342-2342',
        } ]

获取数据

fetchAllData(){
      return this.fetchPost().then(([response,json]) => {
         if(response.status === 200)
         {
            console.log(json.data.shipping)
         0: { name: "Samsung A10", phone: "001-2342-23429"}
         1: {name: "Iphone Xs", phone: "001-12193-1219"}
         }
      })
   }

   fetchPost(){
      const URL = 'http://facicla:5000/api';
      return fetch(URL, {method:'GET',headers:new Headers ({
         'Accept': 'application/json',
         'Content-Type': 'application/json', 
      })})
      .then(response => Promise.all([response, response.json()]));
   }

渲染

render() {
      const { shippings, addNewData} = this.state;
      return (
         <div className="wrapper">
            <div className="row row-eq-height">
               {shippings.map((shipping, key) => (
                  <div className="col-sm-3 col-md-3 col-lg-3" key={key}>
                        <div className="d-flex justify-content-between">
                        <h5 className="fw-bold">{shipping.name}</h5></a>
                        <h5 className="fw-bold">{shipping.phone}</h5></a>

                        </div>                          
                  </div>  
               ))}
            </div>
}

1 个答案:

答案 0 :(得分:1)

尝试一下:

fetchAllData(){
      return this.fetchPost().then(([response,json]) => {
         if(response.status === 200)
         {
            console.log(json.data.shipping)
            this.setState(
          { shippings: Object.values(json.data.shipping)
             //or shippings: json.data.shipping 
          } 

          )


         //0: { name: "Samsung A10", phone: "001-2342-23429"}
         //1: {name: "Iphone Xs", phone: "001-12193-1219"}
         }
      })
   }