Фильтровать массив объектов Json, используя выбранные флажки - Реагировать - PullRequest
0 голосов
/ 12 января 2019

Я новичок, чтобы реагировать. У меня есть массив объектов Json, и я хочу отфильтровать этот массив на основе выбранных флажков. У меня есть несколько флажков в зависимости от города, языка и темы. Пожалуйста, смотрите скриншот ниже enter image description here

Вот мой код для страницы, показанной выше. Как мне реализовать эту функциональность? Я хочу, чтобы, если кто-то установит флажок, данные будут отфильтрованы, а если отменить выбор, то данные также будут перерисованы. Как мне этого добиться?

import React from 'react';
import NavigationBar from './NavigationBar';
import SearchPageResultsStyle from "../assets/css/SearchResultsPage.css"
import Pagination from './Pagination';

class SearchResultsPage  extends React.Component{
    constructor(props) {
        super(props);
        console.log("Printing in the results component: this.props.location.state.data.results")
        console.log(this.props.location.state.data.results)
        this.state = {
            results: this.props.location.state.data.results,
            keyword: this.props.location.state.data.keyword,
            pageOfItems: [],
            city: ''
        };
        this.onChangePage = this.onChangePage.bind(this);
    }

    onChangePage(pageOfItems) {
        // update local state with new page of items
        this.setState({pageOfItems});
    }

    handleCityDelhi(event) {
        this.setState({city: event.target.name})

    }
    render() {

        const renderItems = this.state.pageOfItems.map((item, index) => {
            return (
                <div>
                    <h3 style={{color: '#1a0dab'}} key={index}>{item.text}</h3>
                    <a href={'https://google.com'} key={index}>{item.tweetUrl}</a>
                    <br/>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>topic: </span>{item.topic}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>city: </span>{item.city}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>lang: </span>{item.lang}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>Hashtags: </span></p>
                    <hr/>
                </div>
            )
        })
        return (
            <div>
                <NavigationBar/>
                <h4 style={{textAlign:'center', color:'#1a0dab'}}>Showing search results for <span style={{fontWeight:'bold', fontStyle:'Italic'}}>'{this.state.keyword}'</span></h4>
                <hr/>
                <div className={'wrap'} style={SearchPageResultsStyle}>
                    <div className={'fleft'}>
                        <h4>Topics</h4>
                        <input name={'Crime'} type={'checkbox'} /> Crime
                        <hr/>
                        <h4>City</h4>
                        <input name={'Delhi'} type={'checkbox'} onChange={this.handleCityDelhi}/> Delhi
                        <hr/>
                        <h4>Language</h4>
                        <input name={'Hindi'} type={'checkbox'}/> Hindi
                        <hr/>
                    </div>
                    <div className={'fcenter'}>
                        {renderItems}
                        <Pagination items={this.state.results} onChangePage={this.onChangePage}/>
                    </div>
                    <div className={'fright'}></div>
                </div>
            </div>
        )
    }

}

export default SearchResultsPage;

1 Ответ

0 голосов
/ 12 января 2019

Вы можете использовать состояние для каждого флажка, например, тема, город и язык, а затем установите состояние в обработчике каждого флажка. Затем вы можете отфильтровать массив данных, чтобы показать отфильтрованные данные, например,

const { topic, city, language } = this.state;
// assuming data is array and all the filter values are not empty.
// If empty no need for filter
const filteredData = data.filter(val => {
return (topic.length && topic.includes(val.topic)) ||
(city.length && city.includes(val.city)) ||
(language.length && language.includes(val.language))
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...