【发布时间】: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