我有以下代码,需要在其中添加两个额外的内容,但是我被卡住了,不确定如何做。
我需要添加:
如果类别中没有产品,则NotFound组件将显示一条消息。
通过在输入中输入“全部”,我们应该能够再次从所有类别中看到整个产品列表。
理想情况下,我正在寻找最简单的解决方案,因为我正在学习React。谢谢!
主要组件
import React from 'react';
import Item from './components/Item';
class App extends React.Component {
state = {
items: [
{
title: "The Spice Girls",
price: 10,
category: "Pop",
quantity: 1,
},
{
title: "Beethoven",
price: 5,
category: "Classical",
quantity: 1,
},
{
title: "Bob Marley",
price: 15,
category: "Reggae",
quantity: 1,
}
],
category: " ",
filtered: [],
}
handleChange = e => {
this.setState({category: e.target.value},()=>console.log(this.state.category));
}
handleClick = (event) => {
event.preventDefault()
var newList = this.state.items;
var filteredItems = newList.filter(item => item.category === this.state.category)
this.setState({filtered: filteredItems})
}
render () {
let show;
if(this.state.category !== " "){
show = this.state.filtered.map((item, i) => <Item key = {i} cd={item}/>)
}else{
show = this.state.items.map( (item,i) => <Item key = {i} cd={item}/>)
}
return (
<div>
<h1 className = "title">CD</h1>
<h2>Search music below:</h2>
<form>
Music style: <input onChange = {this.handleChange}></input>
<button onClick = {this.handleClick}>Search</button>
</form>
{show}
</div>
)
}
}
export default App;
项目组件
import React from 'react';
class Item extends React.Component {
render () {
return (
<div className = "items">
<div className = "item">
<h3>{this.props.cd.title}</h3>
<div className = "price">Price: {this.props.cd.price}€</div>
<div className = "quantity">Quantity: {this.props.cd.quantity}</div>
<div className = "category">Category: {this.props.cd.category}</div>
</div>
</div>
)
}
}
export default Item;
答案 0 :(得分:1)
在分析您的代码时,有几件事使我感到困惑,因此将它们共享给您,就好像您将来在团队中工作时,如果其他人可以理解您的代码将很方便。
您的文本框有一个on change事件,与旁边的搜索按钮事件不同。用户期望它是相同的,所以确实令人困惑。
您实际上有2个项目列表,一个是原始项目,一个是未过滤项目,您可以在屏幕上显示的两个项目之间进行切换。有时候您需要一个原始集,这很好,但是也许要确保唯一的presented as such
就是state.items
或state.filtered
。我可能会期望state.filtered
使您的搜索不区分大小写,例如pop应该匹配Pop
如果类别中没有产品,则NotFound组件将显示一条消息。
为此,我首先要修改您的显示逻辑以在相同的过滤列表上工作,只需更改事件功能以操作过滤列表并取消选中其中一个即可。
可能为没有案件的情况添加另一个条件
if (this.state.filtered) {
show = this.state.filtered.map((item, i) => <Item key={i} cd={item} />);
} else {
show = <h1>NoneFound</h1>;
}
通过在输入中输入“全部”,我们应该能够再次从所有类别中看到整个产品列表。
handleClick = event => {
event.preventDefault();
var { category } = this.state;
var newList = this.state.items;
var filteredItems;
if ([" ", "All"].some(t => t === category)) {
filteredItems = newList;
} else {
filteredItems = newList.filter(
item => item.category.toLowerCase() === this.state.category.toLowerCase()
);
}
this.setState({ filtered: filteredItems });
};
对此,我的灵魂在于修改您的onClick事件以正确处理过滤后的列表。
您可以在此处的代码框上看到我的完整信息