【问题标题】:Updating text input state and AJAX search by same value lagging by one character [duplicate]通过延迟一个字符的相同值更新文本输入状态和AJAX搜索[重复]
【发布时间】:2018-02-12 01:29:52
【问题描述】:

我有一个文本输入搜索栏来查找产品,当我输入术语时,它会发出 AJAX 请求以查找匹配项并将其设置为产品状态。但是,它落后了一个字符。 IE 我输入“car”,它正在搜索“ca”,当我输入“cars”时,它搜索“car”。我猜这与 React setState 的工作方式有关。提示如何解决这个问题?

class ProductIndexPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      term: '',
      collection: null,
      products: this.props.products
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({term: event});
    this.searchProducts()
  }
  render() {
    function CreateItem(product) {
      return { 
        url: '/products/' + product.id, 
        attributeOne: product.title,
        attributeTwo: product.variants[0].variant_price,
        attributeThree: '5 prices from $8.99 to $13.99',
        media: <Thumbnail
                  source={product.main_image_src}
                  alt={product.title}
                  size="small"
                />
      }
    }
    function CollectionTitles(collection) {
      return collection.title
    }
    return (
      <Layout>
        <Layout.Section>
          <Card title="Online store dashboard" actions={[{content: 'Edit'}]} sectioned>
            <Card.Section>
              <Stack>
                <TextField 
                  value={this.state.term}
                  label="Keyword Search"
                  placeholder="Enter Term"
                  onChange={this.handleChange}
                />
                <Select
                  value= {this.state.collection}
                  label="Collection"
                  options={ this.props.collections.map(CollectionTitles) }
                  placeholder="Select"
                  //onChange={this.valueUpdater('collection')}
                  //onChange={this.searchProducts('collection')}
                />
              </Stack>
            </Card.Section>
            <Card.Section>
                <ResourceList
                  items={
                      this.state.products.map(CreateItem)
                  }
                  renderItem={(item, index) => {
                    return <ResourceList.Item key={index} {...item} className='Polaris-Card' />;
                  }}
                />
            </Card.Section>
          </Card>
        </Layout.Section>
      </Layout>
    ); 
  }
searchProducts() {
  console.log('In queryProducts');
  console.log('AJAX')
  $.ajax( {
    url: '/products/' + "?term=" + this.state.term, //+ "&collection=" + this.state.collection,
    dataType: 'json',
    success: function(data) {
      console.log('SUCCESS');
      console.log(data)
    this.setState({ products: data });
    }.bind(this),
    error: function(data) {
    }.bind(this)
   });
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    那是因为setState 函数是异步的。因此,当您调用 setState 时,它不会立即设置状态。并且您在调用setState 之后立即调用 api 调用(即当状态尚未更新时)。这就是为什么它在没有最后一个字母的情况下调用 api。

    解决方案:: 给 setState 传递一个回调函数。状态更新时将调用该回调。在该回调中,您可以像这样调用您的 api

    handleChange(event) {
        this.setState({term: event}, () => {
          this.searchProducts()
        });
      }
    

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 2011-12-12
      • 2019-12-15
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      相关资源
      最近更新 更多