Я учусь в React, изучаю электронную практику, но у меня проблема, я действительно хотел создать фильтр для своего приложения.
У меня есть такой код:
class Pagination extends React.Component {
constructor() {
super();
this.state = {
elementsPerPage:3,
currentPage:0,
peoples:[
{id:0, name:"jee"},
{id:1, name:"jiii"},
{id:2, name:"jaa"},
{id:3, name:"joo"},
{id:4, name:"daaa"},
{id:5, name:"hehee"},
{id:6, name:"hoho"},
{id:7, name:"ihihi"},
{id:8, name:"huheue"},
{id:9, name:"haha"},
{id:10, name:"brbr"},
{id:11, name:"ususauasaua"}]
};
this.nextPage = this.nextPage.bind(this);
this.previousPage = this.previousPage.bind(this);
this.searchItem = this.searchItem.bind(this);
}
/* elementsOnScreen () {
const currentState = this.state;
return this.state.numbers
.slice(this.state.currentPage*this.state.elementsPerPage, this.state.currentPage*this.state.elementsPerPage + this.state.elementsPerPage)
.map(number => (<li>{number}</li>));
}
*/
elementsOnScreen () {
const {elementsPerPage, currentPage, peoples} = this.state;
return peoples
.slice(currentPage*elementsPerPage, currentPage*elementsPerPage + elementsPerPage)
.map((peoples)=><li>{peoples.name}</li>);
}
nextPage () {
const {elementsPerPage, currentPage, peoples} = this.state;
if ((currentPage+1) * elementsPerPage < peoples.length){
this.setState({ currentPage: this.state.currentPage + 1 });
console.info(this.state.currentPage)
}
}
previousPage () {
const { currentPage } = this.state;
if (currentPage - 1 >= 0){
this.setState({ currentPage: this.state.currentPage - 1 });
}
}
searchItem (){
console.info(this.state.elementsPerPage)
}
render() {
return (
<div>
<input></input>
<button onClick = {this.searchItem}> Search </button>
<button onClick = {this.previousPage}> Previous </button>
<button onClick = {this.nextPage}> Next </button>
<h1>Names: {this.elementsOnScreen()} </h1>
<h1>Current Page: {this.state.currentPage}</h1>
</div>
);
}
}
ReactDOM.render(
<Pagination/>,
document.getElementById('root')
)<div id = "root"></div>Идея фильтра: Отфильтровать, если было какое-то слово или буква, равные введенному при вводе.
Пример: Набираю букву «а», возвращаю слова:
Кто-нибудь может мне помочь?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вам нужно использовать .filter(), чтобы получить массив объектов, который содержит эту конкретную букву (в вашем случае это «а»), так что:
peoples.filter(item => item.name.includes("a"))
Это вернет вам:
peoples:[
{id:2, name:"jaa"},
{id:4, name:"daaa"},
{id:9, name:"haha"},
{id:11, name:"ususauasaua"}];
Затем вы можете связать .map() с возвращенным массивом и получить свойство name:
peoples.filter(item => item.name.includes("a")).map(item => item.name);
Это вернет вам массив только имен:
["jaa", "daaa", "haha", "ususauasaua"]
Внутри вашей функции elementsOnScreen
elementsOnScreen () {
const { peoples} = this.state;
return (
<div> { peoples.filter(item => item.name.includes("a")).map(item =>
(<li> {item.name}</li>))}
</div>
)
}
Теперь вы получите:
Warning: Each child in an array or iterator should have a unique "key" prop.
Чтобы избежать этого, убедитесь, что внутри вашего .map() задайте уникальное значение ключа для <li>.
.map(item => (<li key= {item.id}> {item.name}</li>));