如何在react中设置动态数据?

时间:2019-01-21 10:35:17

标签: reactjs

我有一系列数据,这些数据在一个数组(json文件)中包含一些对象,它将由react显示。

const Library = [
{
name: "Star Wars"
},
{
name: "Harry Potter"
},
{
name: "Lord of the Rings"
},
{
name: "Star Trek"
},
{
name: "The Fault in Our Stars"
},
{
name: "Number the Stars"
},
{
name: "Blue"
},
{
name: "Act Da Fool"
},
{
name: "The Gilded Cage"
},
{
name:
  "To Get to Heaven First You Have to Die (Bihisht faqat baroi murdagon)"
},
{
name: "Lebanon"
},
{
name: "Tenderness"
},
{
name: "It"
},
{
name: "Locked Out (Enfermés dehors)"
},
{
name: "Waterloo Bridge"
},
{
name: "Set It Off"
},
{
name: "Nil By Mouth"
},
{
name: "Monte Carlo"
},
{
name: "Treasure of the Four Crowns"
},
{
name: "Donnie Darko"
},
{
name: "Cry-Baby"
},
{
name: "Juan of the Dead (Juan de los Muertos)"
},
{
name: "Constant Nymph, The"
}
];

// Main App Component
 class App extends React.Component {
 constructor(props){
 super();
 this.state = {
library: null,
perPage: 1,
currentPage: 1,
maxPage: null,
filter: ""
 };
}
componentDidMount() {
 this.reorganiseLibrary();
 }

// Calculates the library
   reorganiseLibrary = () => {
   const { filter, perPage } = this.state;
   let library = Library;
   console.log(library)

   if (filter !== "") {
    library = library.filter(item =>
    item.hotelinfo.hotelsearch.realname.toLowerCase().includes(filter)
   );
   }

  library = _.chunk(library, perPage);

   this.setState({
    library,
    currentPage: 1,
    maxPage: library.length === 0 ? 1 : library.length
    });
   };

  // Previous Page
   previousPage = () =>
   this.setState(prevState => ({
   currentPage: prevState.currentPage - 1
  }));

// Next Page
  nextPage = () =>
  this.setState(prevState => ({
  currentPage: prevState.currentPage + 1
 }));

// handle filter
   handleFilter = evt =>
  this.setState(
   {
    filter: evt.target.value.toLowerCase()
  },
  () => {
    this.reorganiseLibrary();
  }
);

 // handle per page
  handlePerPage = (evt) =>
  this.setState({
   perPage: evt.target.value 
   }, () => this.reorganiseLibrary());

 // handle render of library
  renderLibrary = () => {
  const { library, currentPage } = this.state;
  if (!library || (library && library.length === 0)) {
  return <div>No results</div>;
  }
   return library[currentPage - 1].map(item => (
    <div key={item.hotelinfo.hotelsearch.realname}>{item.hotelinfo.hotelsearch.realname}</div>
   ));
   };

 render() {
    const { library, currentPage, perPage, maxPage } = this.state;
     return (
     <div className="library">
      <h1>Library</h1>
      <div className="d-flex">
          <div className="flex-fill">
              <label className="library__filter-label">Filter</label>
              <input value={this.state.filter} onChange={this.handleFilter} />
          </div>
          <div className="flex-fill text-right">
              <label className="library__per-page-label">Per page</label>
              <input placeholder="per page" value={this.state.perPage} onChange={this.handlePerPage} />
          </div>
      </div>
      <div className="library__book-shelf">
          {this.renderLibrary()}
      </div>
      <div className="d-flex">
          <div className="flex-fill">
            {currentPage !== 1 && (
              <button onClick={this.previousPage}>Previous</button>
            )}
          </div>
          <div className="flex-fill text-right">
            {(currentPage < maxPage) && (
              <button onClick={this.nextPage}>Next</button>
            )}
          </div>
      </div>
      <div className="library__page-info text-right">
          {this.state.currentPage} of {this.state.maxPage}
      </div>
  </div>
  );
  }
  }
 ReactDOM.render(<App/>, document.getElementById('root')); 

Library的数据将是动态的,并且该数据将通过ajax请求从另一页发送到此页面,但是您可以看到数据是静态设置的。如何动态设置图书馆数据。 我尝试下面的代码Biy出现此错误:  ReferenceError:库未定义

Component { 
  constructor(props){ 
  super(); 
  this.state = { 
  Library:[],
  library: null,
   ..... 
    };
  $.ajax({ 
  url:"/json.bc", 
  type:"post",
  data:{ 
  cityid:"1182348",
  rooms:JSON.stringify({"rooms":[{"adultcount":"1","childcountandage":"0"}]}), 
    },
  success:(result)=>{ 
  this.setState({Library: eval(result)}); } }) }
  . . . 
  }

修改后的代码:

class App extends React.Component {
 constructor(props){
 super();
 this.state = {
 Library:[],
 library: null,
 perPage: 1,
 currentPage: 1,
 maxPage: null,
 filter: "",
 };
 }
  componentDidMount() {
  $.ajax({ 
  url:"/test1.bc", 
  type:"post",
   data:{
    cityid:"1182348",
    rooms:JSON.stringify({"rooms":[{"adultcount":"1","childcountandage":"0"}]}),
                },
   success:(result)=>{ 
   this.setState({Library: eval(result)}); } 

   })}
   componentDidMount() {
     this.reorganiseLibrary();
    }

// Calculates the library
   reorganiseLibrary = () => {
   const { filter, perPage } = this.state;
   let library = Library;
   console.log(library)

    if (filter !== "") {
      library = library.filter(item =>
      item.hotelinfo.hotelsearch.realname.toLowerCase().includes(filter)
     );
     }

     library = _.chunk(library, perPage);
     this.setState({
      library,
      currentPage: 1,
      maxPage: library.length === 0 ? 1 : library.length
       });
      };

    // Previous Page
       previousPage = () =>
       this.setState(prevState => ({
        currentPage: prevState.currentPage - 1
       }));

   // Next Page
   nextPage = () =>
    this.setState(prevState => ({
     currentPage: prevState.currentPage + 1
   }));

   // handle filter
    handleFilter = evt =>
    this.setState(
     {
       filter: evt.target.value.toLowerCase()
     },
     () => {
      this.reorganiseLibrary();
     }
    );

  // handle per page
    handlePerPage = (evt) =>
     this.setState({
     perPage: evt.target.value 
}, () => this.reorganiseLibrary());

   // handle render of library
   renderLibrary = () => {
    const { library, currentPage } = this.state;
if (!library || (library && library.length === 0)) {
  return <div>No results</div>;
}
return library[currentPage - 1].map(item => (
  <div key={item.hotelinfo.hotelsearch.realname}>{item.hotelinfo.hotelsearch.realname}</div>
));
};

render() {
const { library, currentPage, perPage, maxPage } = this.state;
return (
  <div className="library">
      <h1>Library</h1>
      <div className="d-flex">
          <div className="flex-fill">
              <label className="library__filter-label">Filter</label>
              <input value={this.state.filter} onChange={this.handleFilter} />
            </div>
          <div className="flex-fill text-right">
              <label className="library__per-page-label">Per page</label>
              <input placeholder="per page" value={this.state.perPage} onChange={this.handlePerPage} />
          </div>
      </div>
      <div className="library__book-shelf">
          {this.renderLibrary()}
      </div>
      <div className="d-flex">
          <div className="flex-fill">
            {currentPage !== 1 && (
              <button onClick={this.previousPage}>Previous</button>
            )}
          </div>
          <div className="flex-fill text-right">
            {(currentPage < maxPage) && (
              <button onClick={this.nextPage}>Next</button>
            )}
          </div>
      </div>
      <div className="library__page-info text-right">
          {this.state.currentPage} of {this.state.maxPage}
      </div>
  </div>
);
 }
 }
ReactDOM.render(<App/>, document.getElementById('root')); 

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

getData = (callback) => {
 $.ajax({ 
   url:"/json.bc", 
   type:"post",
   data:{ 
   cityid:"1182348",
   rooms:JSON.stringify({"rooms":[{"adultcount":"1","childcountandage":"0"}]}), 
    },
   success:(result)=>{ 
    callback(eval(result))
   }
   . . . 
   }
}

setData = () => {
 this.getData(data => { this.setState({ Library: data }) } )
}

答案 1 :(得分:0)

尝试在componentDidMount()设置状态下调用ajax调用。

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