我正在尝试使用该filter()方法从数组中过滤掉项目,如果数组的长度小于某个数字,则在Reactjs中。到目前为止,我还无法做到这一点。
代码示例:
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
itemNumber: 2,
items: [
{ text: "Item 1" },
{ text: "Item 2" },
{ text: "Item 3" },
{ text: "Item 4" }
]
}
}
filterItem = () => {
if ( this.state.items.length > this.state.itemNumber ) {
console.log('Items length is higher');
let newItems = this.state.items.filter(item => {
return item < this.state.itemNumber;
});
console.log(newItems);
} else {
console.log('Items length is lower');
}
};
render() {
const { items } = this.state;
return (
<div>
<ul>
{ this.state.items.map(item =>
(
<li key={item.id}>
{ item.text }
</li>
)
)}
</ul>
<button onClick={this.filterItem}>Filter items!</button>
</div>
)
}
}
编辑:
解决方案在这里。