Мне нужно дважды щелкнуть по флажку, чтобы отфильтровать свои карты в React

#javascript #reactjs

Вопрос:

У меня есть проблема, из-за которой я должен дважды щелкнуть по своим флажкам в разделе «Фильтр», чтобы отфильтровать карточки ресторанов, например, значение this.state.Тип1 является ложным, если я нажму в первый раз, он все равно будет ложным, даже если он должен измениться в зависимости от значения флажка, поэтому мне нужно нажать второй раз, чтобы сделать его истинным, вы можете мне помочь, пожалуйста

это и есть код

 import React, { Component } from 'react';
import axios from 'axios';
import App from "../../App";
import Cards from "../../Card";

function CreateCards(resturants) {

//Handel the Music, Wifi, Partition (to transfer it from bolean form into string)
    let ifMusic;
    let ifWifi;
    let ifPartition;

    if (resturants.Music == true){
        ifMusic = "Music";
    }else{
        ifMusic = "No Music";
    }

    if (resturants.Wifi == true){
        ifWifi = "Wifi";
    }else{
        ifWifi = "No Wifi";
    }

    if (resturants.Partition == true){
        ifPartition = "Partition";
    }else{
        ifPartition = "No Partition";
    }
        
    return(
        <Cards
            key={resturants._id}
            theCardId={resturants._id}
            placeName={resturants.Name}
            stars={resturants.Rating}
            PRating={resturants.PRating}
            music= {ifMusic}
            img={resturants.icon} // need uploads file
            status={Status(resturants.OpenTime, resturants.CloseTime)}
            descreption={resturants.Description}
            wifi={ifWifi}
            partition={ifPartition}
        />
    );
}

// Check if the place is open or closed depending on the work hours
function Status (Open, Close){
    const date = new Date();
    var hours = date.getHours();
    const red = 'red';
    const green = 'green';
    if ((Open <= hours) amp;amp; (hours < Close)){
        return "Open";
    }else{
        return "Close";
    }
}


export default class Resturants extends Component {
//constructor elemnts in login
    constructor(props){
        super(props);

//intialy no data enterd // the types are the filters for each place such as music wifi etc
        this.state = {
            resturants: [],
            Type1: false,
            Type2: false,
            Type3: false,
            Type4: false,
            Type5: false,
            filteredRestraunts:[],
            noPlaceFound: false
    }
    this.onChangeMusic = this.onChangeMusic.bind(this);
    this.onChangeWifi = this.onChangeWifi.bind(this);
    this.onChangePartition = this.onChangePartition.bind(this);
    this.onChangePriceRatinglow = this.onChangePriceRatinglow.bind(this);
    this.onChangePriceRatinghigh= this.onChangePriceRatinghigh.bind(this);
}
componentDidMount(){
    //Get Resturants data, filteredRestraunts used for filtring and sorting the cards
    axios.get('http://localhost:3000/places')
        .then(resp => {
            // console.log(resp)
            this.setState({
                resturants: resp.data,
                filteredRestraunts:resp.data
        })
    })
}

//========================================================//
// Filters
onChangeMusic(e){
    this.setState({Type1: e.target.checked})
    // console.log(this.state.Type1);
    let copy;
    if(this.state.Type1 === true){
        copy =  this.state.filteredRestraunts.filter(Type => {return Type.Music === this.state.Type1})
        this.setState({ filteredRestraunts: copy })
        if(copy.length === 0){
            this.setState({noPlaceFound: true})
        }
    }else{
        copy =this.state.filteredRestraunts;
        this.setState({ filteredRestraunts: copy })
    } 
}

onChangeWifi(e){
    this.setState({Type2: e.target.checked})
    // console.log(this.state.Type2);
    let copy;
    if(this.state.Type2 === true){
        copy =  this.state.filteredRestraunts.filter(Type => {return Type.Wifi === this.state.Type2})
        this.setState({ filteredRestraunts: copy })
        if(copy.length === 0){
            this.setState({noPlaceFound: true})
        }
    }else{
        copy =this.state.filteredRestraunts;
        this.setState({ filteredRestraunts: copy })
    } 
}

onChangePartition(e){
    this.setState({Type3: e.target.checked})
    // console.log(this.state.Type3);
    let copy;
    if(this.state.Type3 === true){
        copy =  this.state.filteredRestraunts.filter(Type => {return Type.Partition === this.state.Type3})
        this.setState({ filteredRestraunts: copy })
        if(copy.length === 0){
            this.setState({noPlaceFound: true})
        }
    }else{
        copy =this.state.filteredRestraunts;
        this.setState({ filteredRestraunts: copy })
    } 
}

//========================================================//
// Sort By
onChangePriceRatinglow(e){
    this.setState({Type4: e.target.checked})
    // console.log(this.state.Type4);
    let copy;
    if(this.state.Type4 === true){
        copy =  this.state.filteredRestraunts.sort((a,b) => { return a.PRating.length - b.PRating.length})
        this.setState({ filteredRestraunts: copy })
        if(copy.length === 0){
            this.setState({noPlaceFound: true})
        }
    }else{
        copy =this.state.filteredRestraunts;
        this.setState({ filteredRestraunts: copy })
    }
}

onChangePriceRatinghigh(e){
    this.setState({Type5: e.target.checked})
    // console.log(this.state.Type5);
    let copy;
    if(this.state.Type5 === true){
        copy =  this.state.filteredRestraunts.sort((a,b) => { return b.PRating.length - a.PRating.length})
        this.setState({ filteredRestraunts: copy })
        if(copy.length === 0){
            this.setState({noPlaceFound: true})
        }
    }else{
        copy =this.state.filteredRestraunts;
        this.setState({ filteredRestraunts: copy })
    }
}
//========================================================//

render(){
    
    return(
        <div className="flexthem">
            <div className="Filters">
                <h4>Filters</h4>
                <label>Music
                <input className="Checkbox" type="checkbox"  id="Type1"  onChange={this.onChangeMusic}></input></label>
                <label>Wifi
                <input className="Checkbox" type="checkbox"  id="Type2"  onChange={this.onChangeWifi}></input></label>
                <label>Partiotion
                <input className="Checkbox" type="checkbox"  id="Type3"  onChange={this.onChangePartition}></input></label>
                <label>Price: Sort by</label>
                <label>Lowest to heighest
                <input type="radio" className="RadioBox" id="Type4" onClick={this.onChangePriceRatinglow}></input></label>
                <label>heighest to Lowest
                <input type="radio" className="RadioBox" id="Type5" onClick={this.onChangePriceRatinghigh}></input></label>
            </div>
            <div className="general-card"> 
                {this.state.filteredRestraunts.map(CreateCards)}
            </div>
            <h1 className="noPlaceFound" style={{display: this.state.noPlaceFound ? 'block' : 'none' }}> No place found</h1>
        </div>
    );
}
}
 

Ответ №1:

Когда вы это сделаете:

 this.setState({Type2: e.target.checked})
if(this.state.Type2 === true){
 

this.state.Type2 не будет обновляться до следующего рендеринга, поэтому if проверка по-прежнему проверяет старое значение, и только в этом условии вы фактически фильтруете. Вместо этого вам нужно сделать:

  if(e.target.checked === true){