使用分页进行反复搜索而不使用double setState

时间:2017-09-01 15:35:37

标签: javascript reactjs pagination state

我正在React中使用分页实现搜索。到目前为止,我发现了很少的例子,但他们在AJAX调用后端之前和之后都使用了双setState()的代码。例如,我目前的解决方案是:

import React from "react"
import PropTypes from "prop-types"

import SearchField from "components/SearchField"
import SearchResults from "components/SearchResults"

import Item from "models/Item"

class Search extends React.Component {
  constructor() {
    super()
    this.state = {
      query: "",
      page: 1,
      foundItems: []
    }
    this.handleSearch = this.handleSearch.bind(this)
    this.handlePageChange = this.handlePageChange.bind(this)
  }

  updateSearchResults() {
    const query = this.state.query
    const params = {
      page: this.state.page
    }
    Item.search(query, params).then((foundItems) => {
      this.setState({ foundItems })
    })
  }

  handleSearch(event) {
    this.setState({
      query: event.target.value
    }, this.updateSearchResults)
  }

  handlePageChange(data) {
    this.setState({
      page: data.selected + 1
    }, this.updateSearchResults)
  }

  render() {
    return (
      <div className="search">
        <SearchField onSearch={this.handleSearch} />
        <SearchResults
            onPageChange={this.handlePageChange}
            onSelect={this.props.onSelect}
            items={this.state.foundItems}
        />
      </div>
    )
  }
}

Search.propTypes = {
  onSelect: PropTypes.func.isRequired
}

export default Search

我知道我可以更改updateSearchResults的接口以接收查询和页面作为参数然后我可以避免首先setState传递值,但它看起来不是一个好的解决方案,因为当搜索参数列表增长(例如排序顺序,页面大小,过滤器)时,它会变得有点笨拙。另外,我不喜欢以这种方式在handleSearchhandlePageChange函数中使用手动状态预管理的想法。我正在寻找更好的实施方案。

1 个答案:

答案 0 :(得分:0)

我不完全确定您的要求,但您可以通过执行以下操作来优化您的代码:

class Search extends React.Component {
  constructor() {
    super()

    this.page = 1;
    this.query = "";
    this.state = {
      foundItems: []
    }
    this.handlePageChange = this.handlePageChange.bind(this)
  }

  updateSearchResults(event) {    
   if(typeof event === "object")
      this.query = event.target.value;

    const params = {
      page: this.page
    }
    Item.search(this.query, params).then((foundItems) => {
      this.setState({ foundItems })
    })
  }

  handlePageChange(data) {    
    this.page = data.selected + 1;
    this.updateSearchResults();
  }

  render() {
    return (
      <div className="search">
        <SearchField onSearch={this.updateSearchResults} />
        <SearchResults
            onPageChange={this.handlePageChange}
            onSelect={this.props.onSelect}
            items={this.state.foundItems}
        />
      </div>
    )
  }
}