使用React中的map方法过滤结果



我想用模式内的数字过滤数组,并获得小于或等于模式内数字的值。然后在<li>中使用map方法显示结果但不幸的是,马斯克不在这里工作,我不知道哪里有问题

class AvailableProducts extends React.Component {
constructor(props) {
super(props);
}
render() {
const Products = [
{ id: "1", name: "Item1", price: 10000 },
{ id: "2", name: "Item2", price: 20000 },
{ id: "3", name: "Item3", price: 32000 },
{ id: "4", name: "Item4", price: 45000 },
{ id: "5", name: "Item5", price: 12000 },
{ id: "6", name: "Item6", price: 52000 },
{ id: "7", name: "Item7", price: 67000 },
{ id: "8", name: "Item8", price: 40000 },
];
const budge = this.props.budge;
const result = Products.filter(price => (price <= budge));
const showResuli = result.map((Product) => (
<li key={Product.id}>{Product}</li>
));
return (
<fieldset>
<legend>Your Result</legend>
<ul>{showResuli}</ul>
</fieldset>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { budget: "35000" };
}
render() {
return (
<div>
<div>
<label>Enter Price</label>
</div>
<AvailableProducts budge={this.state.budget} />
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

它被拼接为过滤数组的行。

const result = Products.filter(price <= budge);

您需要为filter函数提供一个函数。

像这样:

const result = Products.filter(({price}) => (price <= budge));

并且你不能呈现一个";对象";就像你在这里做的那样:

result.map(Product => (
<li key={Product.id}>{Product}</li> // but `Product.name` or thing like this
))

下面是一个函数示例:

class AvailableProducts extends React.Component {
constructor(props) {
super(props);
}
render() {
const Products = [
{ id: "1", name: "Item1", price: 10000 },
{ id: "2", name: "Item2", price: 20000 },
{ id: "3", name: "Item3", price: 32000 },
{ id: "4", name: "Item4", price: 45000 },
{ id: "5", name: "Item5", price: 12000 },
{ id: "6", name: "Item6", price: 52000 },
{ id: "7", name: "Item7", price: 67000 },
{ id: "8", name: "Item8", price: 40000 },
];
const budge = this.props.budge;
const result = Products.filter(({price}) => (price <= budge));
return (
<fieldset>
<legend>Your Result</legend>
<ul>
{result.map(Product => (
<li key={Product.id}>{Product.name}</li>
))}
</ul>
</fieldset>
);
}
}

最新更新