我有一个应用程序来区分可用和不可用优惠券,当用户点击可用优惠券时,优惠券将转到>不可用部分(反之亦然),一切正常。但是,如果我在搜索框中搜索优惠券,就会发生错误,结果我无法获取搜索到的优惠券的初始索引(它总是会更改为索引0)
例如,Coupon B
应该有索引 1,但是当我输入 Coupon B
时在搜索框中,索引将更改为 0,这会破坏我的 changedHandler
逻辑。我该如何解决这个问题?
您可以通过此链接 https://go-coupon-d0fe4.firebaseapp.com/ 查看我的应用程序的运行情况
MainContainer.Jsx
state = {
availableCoupon: ['Coupon A', 'Coupon B', 'Coupon C', 'Coupon D'],
nonAvalailable: ['filter0', 'filter1', 'filter2', 'filter3'],
text: ''
};
searchHandler = text => {
this.setState({ text });
};
changedHandler = i => {
console.log(i);
const r = window.confirm('Use Coupon?');
if (r) {
let newItems = [...this.state.nonAvalailable];
let updatedItems = this.state.availableCoupon.splice(i, 1);
newItems.push(...updatedItems);
this.setState({
nonAvalailable: newItems
});
console.log('THIS IS NEW ITEMS ' + updatedItems);
}
return false;
};
render(){
return(
<SearchBox
searchTerm={this.state.text}
filteredList={this.state.availableCoupon}
searchHandler={this.searchHandler}
/>
<FilteredItem
changed={this.changedHandler}
searchTerm={this.state.text}
availableCoupon={this.state.availableCoupon}
/>
)
}
SearchBox.jsx
<Input
onChange={e => this.props.searchHandler(e.target.value)}
value={this.props.text}
type="text"
name="coupone"
id="exampleCoupon"
placeholder="Coupon Goes Here"
/>
filteredItem.jsx
{this.props.availableCoupon
.filter(
item =>
`${item}`
.toUpperCase()
.indexOf(this.props.searchTerm.toUpperCase()) >= 0
)
.map((item, index) => {
return (
<Col key={index} className="mt-3" md="2" lg="2" sm="3" xs="4">
<Card onClick={() => this.props.changed(index)}>
<CardBody>
<CardTitle>{item}</CardTitle>
</CardBody>
</Card>
</Col>
);
})}
最佳答案
因此,它不起作用的原因是您所依赖的 key
属性在您每次实际搜索时都会发生变化。所以你有两个选择:
1 - 使用对象而不是字符串,这更像现实世界。对象具有唯一的属性,并且不应更改,例如 id,或者可能是其他属性。例如[{name: 'ABCDE', id: 1}, {name: 'PQRST', id: 2}]
。所以你可以在它们上构建过滤、删除等。
2 - 继续使用字符串一段时间,而是依赖初始数组的每个元素的索引。 这就是我的意思:
{this.props.availableCoupon
.filter(
item =>
`${item}`
.toUpperCase()
.indexOf(this.props.searchTerm.toUpperCase()) >= 0
)
.map((item, index) => {
return (
let ind = this.props.availableCoupon.indexOf(item);
<Col key={index} className="mt-3" md="2" lg="2" sm="3" xs="4">
<Card onClick={() => this.props.changed(ind)}>
<CardBody>
<CardTitle>{item}</CardTitle>
</CardBody>
</Card>
</Col>
);
})}
第二个是一个非常快速的解决方案,但在现实世界中你通常不会这样做。只要在现实世界中我们拥有每个对象及其相关的稳定 id
,您可能就不需要它。
关于javascript - React 如何在搜索中获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50652781/