SearchPage.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // This is the root component for #search-page
  2. import React from 'react';
  3. import SearchForm from './SearchForm';
  4. import SearchResult from './SearchResult';
  5. import axios from 'axios'
  6. export default class SearchPage extends React.Component {
  7. constructor(props) {
  8. super(props);
  9. this.state = {
  10. location: location,
  11. searchingKeyword: this.props.query.q || '',
  12. searchedPages: [],
  13. searchError: null,
  14. }
  15. this.search = this.search.bind(this);
  16. }
  17. componentDidMount() {
  18. if (this.state.searchingKeyword !== '') {
  19. this.search({keyword: this.state.searchingKeyword});
  20. this.setState({searchedKeyword: this.state.keyword});
  21. }
  22. }
  23. static getQueryByLocation(location) {
  24. let search = location.search || '';
  25. let query = {};
  26. search.replace(/^\?/, '').split('&').forEach(function(element) {
  27. let queryParts = element.split('=');
  28. query[queryParts[0]] = queryParts[1];
  29. });
  30. console.log(query);
  31. return query;
  32. }
  33. search(data) {
  34. const keyword = data.keyword;
  35. if (keyword === '') {
  36. this.setState({
  37. searchingKeyword: '',
  38. searchedPages: [],
  39. });
  40. return true;
  41. }
  42. this.setState({
  43. searchingKeyword: keyword,
  44. });
  45. axios.get('/_api/search', {params: {q: keyword}})
  46. .then((res) => {
  47. if (res.data.ok) {
  48. this.setState({
  49. searchingKeyword: keyword,
  50. searchedPages: res.data.data,
  51. });
  52. }
  53. // TODO error
  54. })
  55. .catch((res) => {
  56. // TODO error
  57. });
  58. };
  59. render() {
  60. return (
  61. <div>
  62. <div className="header-wrap">
  63. <header>
  64. <SearchForm
  65. onSearchFormChanged={this.search}
  66. keyword={this.state.searchingKeyword}
  67. />
  68. </header>
  69. </div>
  70. <SearchResult pages={this.state.searchedPages} />
  71. </div>
  72. );
  73. }
  74. }
  75. SearchPage.propTypes = {
  76. query: React.PropTypes.object,
  77. };
  78. SearchPage.defaultProps = {
  79. //pollInterval: 1000,
  80. query: SearchPage.getQueryByLocation(location || {}),
  81. };