【发布时间】:2017-10-10 03:14:35
【问题描述】:
所以问题如下:我有一个搜索函数,它获取的是从另一个地方传递的默认值,搜索有效,但只有当它获得新输入时,因此如果我传递“Dress”它不会在我更改输入内容之前调用我的 api 函数。
我已经尝试了 setInitialState() 之类的所有方法,但没有任何显着的成功。
如您所见,我从 Searchbar 获得了一个 onTermChange,它被传递给 handleTermChange,然后更新我的产品:[],但我需要 this.props.location.query 作为默认搜索词,因为这是传递的变量。
handleTermChange = (term) => {
const url = `http://localhost:3001/products?title=${term.replace(/\s/g, '+')}`;
request.get(url, (err, res) => {
this.setState({ products: res.body })
});
};
render () {
return (
<div className='col-md-12' style={{ margin: '0 auto' }}>
<div className='row searchPageHeader' style={{ padding: '10px', backgroundColor: '#1ABC9C' }}/>
<SideMenu />
<SearchBar onTermChange={this.handleTermChange}
defaultValue={this.props.location.query}/>
<ProductList products={this.state.products}
onProductSelect={selectedProduct => this.openModal(selectedProduct)}/>
<ProductModal modalIsOpen={this.state.modalIsOpen}
selectedProduct={this.state.selectedProduct}
onRequestClose={ () => this.closeModal() }/>
<Footer />
</div>
);
}
【问题讨论】:
-
所以你想在组件挂载时自动执行
location.query值的搜索? -
是的,我想自动将我的 products 设置为等于通过 location.query 传递的字符串,所以我的位置查询基本上应该通过handleTermChange 并更新我的产品列表
标签: reactjs