如何在react中显示数据

时间:2019-02-12 07:19:48

标签: reactjs

我将在单击按钮后立即通过ajax()请求调用一些数据。

我有一系列数据,这些数据在一个数组(json文件)中包含一些对象,它将通过react显示出来。每个项目都有一个onClick函数。单击它会调用ajax()请求。主要问题是我无法处理ajax()请求的结果。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      DetailsRoom: {},
    };
  }
  .
  .
  .
  .
  render() {
    const { data } = this.state;
    const renderInfo = data.map((item, i) => {
      return (
        <div class="item">
          <div onClick={e => this.showDiv(e, item, i)}>Click</div>
          <div>{this.state.DetailsRoom[i]}</div>
        </div>
      );
    });
    return <div>{renderInfo}</div>;
  }

  showDiv = (e, element, i) => {
    var mainprovider = element.id.provider;
    var optionId = element.families[0].optionId;
    var return_Room = (function() {
      var tmp = null;
      $.ajax({
        async: false,
        type: 'POST',
        global: false,
        dataType: 'html',
        url: 'showAllRooms.bc',
        data: {data},
        success: response => {
          tmp = response;
        },
      });
      return tmp;
    })();
    return this.setState(prevState => ({
      DetailsRoom: {
        ...prevState.DetailsRoom,
        [i]: this.renderDetailsRoom(eval(return_Room), i),
      },
    }));
  };
  // The result of showDiv() :

  [{
    families: [{}, {}, {}, {}],
  }];

  renderDetailsRoom(DetailsRoom, i) {
    let lenfamilies = DetailsRoom.families.length;
    console.log(lenfamilies); /// TypeError: "DetailsRoom.families is undefined" ///
  }
}
ReactDOM.render(<App />, document.getElementById('Result'));

修改

   fetch('/showAllRooms.bc', {
     method: 'POST',
      body: 'mainprovider='+JSON.stringify(mainprovider)+'&optionId='+optionId+''
   },)
   .then(response => response.text())
    .then(text => {
    var Maindata = JSON.parse(text.replace(/\'/g, '"'))
    this.setState(prevState => ({
    DetailsRoom: {
     ...prevState.DetailsRoom,
    [i]: this.renderDetailsRoom(eval(Maindata), i),
    },
    }))
  }).catch(error => console.error(error))

Edit2 : 成功回应: [{'families':[{'availablerooms':[{'info':{'room':'1/3 pax','cost':0.0,'availability':'available','withbed':0, 'withbed':0,'adults':1,'infant':0,'roomid':'0','double':``}}]],'isRefundable':'false','optionId':'eydvZmZlcmlkJzogJzIkMiQ5MGVlNTZlNS1mYmE3LTQyYYYYYYYYNYYYYYYYYYYYY =','markups':{'totalprovider':10256500.0,'value':{},'totalmarkup':0},'markupsuplier':{'totalmain':10256500.0,'value':{},'totalsuplier': 0},'totalPrice':10256500.0,'totalCom':10256000.0,'commissioncost':0,'services':'-','comdetails':{'type':'number','val':0}}}, {'availablerooms':[{'info':{'room':'1/3 pax','cost':0.0,'availability':'available','withbed':0,'withoutbed':0,'成人'':1,'婴儿':0,'roomid':'0','double':''}}],'isRefundable':'false','optionId':'eydvZmZlcmlkJzogJzIkMiQ5OWM3OWYzOC00MzE4LTRjZDktOTkxNy05NGIWYm' {'totalprovider':15382600.0,'value':{},'totalmarkup': 0},'markupsuplier':{'totalmain':15382600.0,'value':{},'totalsuplier':0},'totalPrice':15382600.0,'totalCom':15383000.0,'commissioncost':0,'services': '-','comdetails':{'type':'number','val':0}},{'availablerooms':[{'info':{'room':'1/3 pax','cost ':0.0,'availability':'available','withbed':0,'withoutbed':0,'adults':1,'infant':0,'roomid':'0','double':' }}],'isRefundable':'false','optionId':'eydvZmZlcmlkJzogJzIkMiRhODMyMzVhZi0wMmZlLTQ1MWEtYmFiYi1lNTM3M2EyOTY2NmUnLCAnc2VhcmNoaW ='''','','','',' {'totalmain':20513000.0,'value':{},'totalsuplier':0},'totalPrice':20513000.0,'totalCom':20513000.0,'commissioncost':0,'services':'-','comdetails' :{'type':'number','val':0}}}}]

2 个答案:

答案 0 :(得分:0)

在调用ajax调用的成功方法之后执行setState。 例如,

success: response => {
  this.setState({
    DetailsRoom: response
  })
}

答案 1 :(得分:0)

请使用axiosjavascript fetch APIreact中进行api调用。您应该setState在ajax调用的成功中。您可以在showDiv中使用以下命令:

$.ajax({
    async: false,
    type: 'POST',
    global: false,
    dataType: 'html',
    url: 'showAllRooms.bc',
    data: {data},
    success: response => {
      this.setState(prevState => ({
        DetailsRoom: {
         ...prevState.DetailsRoom,
        [i]: this.renderDetailsRoom(response.data, i),
      },
     }));
    },
  });