在React中设置动态数据

时间:2019-01-22 07:05:08

标签: reactjs

我有一系列数据,这些数据在一个数组(json文件)中包含一些对象。我将静态设置Library的数据,并且一切都很好,但是Library将是动态的,并且数据将从另一页发送通过ajax请求访问此页面如何动态设置Library的数据?

const Library = [{'id': '5c0b6cd9e1382352759fbc25', 'hotelinfo': {'name': 'Korston Hotel', 'hotelsearch': {'realname': 'Korston Hotel Moscow', 'hotelid': 1011702.0, 'hotelimage': 'htl207110100001', 'countryid': 1002035.0, 'ecountryname': 'Russia', 'countryname': '', 'cityid': 1182348.0, 'ecityname': 'Moscow', 'cityname': '', 'star': 4.0, 'services': 'H.B', 'desc': ' ', 'enable': '1', 'delete': '0'}, 'information': {'viewname': ''}, 'validatedate': {'fdate': '1397-12-01', 'tdate': '1397-12-29', 'tdateid': 10592.0, 'fdateid': 10564.0}}, 'families': [{'availablerooms': [{'info': {'room': 'Single', 'cost': 2400.0, 'availability': 'onrequest', 'withbed': 0.0, 'withoutbed': 0.0, 'adults': 1.0, 'infant': 0.0, 'roomid': '1011702_483587', 'double': '0'}}], 'optionId': '1011702_483587@@@5c0b6cd9e1382352759fbc25', 'totalPrice': 2400.0, 'services': 'H.B', .....]
class App extends React.Component {
    constructor(props){
        super();
        this.state = {
            library: null,
            perPage: 1,
            currentPage: 1,
            maxPage: null,
            filter: "",
        };
    }
   .
   .
   .
 }
 ReactDOM.render(<App/>, document.getElementById('root'));

我尝试下面的代码,但出现错误:ReferenceError:库未定义。

Component { 
    constructor(props){ 
        super(); 
        this.state = { 
            Library:[],
            library: null,
            ..... 
        };
    }
        componentDidMount() {
          $.ajax({ 
          url:"/test1.bc", 
          type:"post",
                data:{
                    cityid:"1182348",
                    fdate:"1397-12-13", 
                    tdate:"1397-12-16", 
                    userid:"0",
                    rooms:JSON.stringify({"rooms":[{"adultcount":"1","childcountandage":"0"}]}),
                },
       success:(result)=>{ 
       this.setState({Library: eval(result)}); } 

     }) }
}

1 个答案:

答案 0 :(得分:0)

您可以在componentDidMount生命周期方法中动态设置数据,而不是在constructor中或作为实例变量对其进行初始化。

componentDidMount() {
  const data = {};

  // fetch the data via $.ajax, fetch, or axios, etc

  this.setState({data: data});
}

对于您的情况,它类似于:

componentDidMount() {
    $.ajax({ 
        url:"/json.bc", 
        type:"post",
        data:{ 
        cityid:"1182348",
        rooms:JSON.stringify({"rooms": [{"adultcount":"1","childcountandage":"0"}]}), 
    },
    success: result => { 
        this.setState({library: eval(result)}); // set this to 'library' instead of 'Library', since you set the variable name as 'library' in the constructor
    });
}