setState() 不给数组赋值

问题描述

我在构造函数中有如下状态

this.state = {
type: {
            Building: false,House : false,Plot : false,FarmHouse : false,},location : {
            Lahore : false,Islamabad : false,Karachi : false,Peshawar : false
        },clicked : false,propertyFound: []
    }
    

我从另一个包含以下格式数据的文件中导入了 {PropertyData}

export const PropertyData = [
    {   
        id:0,propertyType: 
                    "Building",location : "Lahore",society : "wapdatown",{   
        id:1,propertyType: 
                    "House",location : "Islamabad",society : "faisaltown",{   
        id:2,propertyType: 
                    "Plot",location : "Karachi",society : "johartown",{   
        id:3,}
      
]

现在我希望根据用户的输入过滤 {PropertyData} 中的数据。 locationValues 包含用户给出的城市的值。 findCity() 过滤数据并返回包含用户输入的位置 === 城市的数据。

findCity(){
        let newArray = [];
        for(let locationValues in this.state.location){
            if(this.state.location[locationValues] === true ){
                newArray = PropertyData.filter(element => 
                    element.location === locationValues   
                )
            }
            this.setState({propertyFound : newArray},() => console.log(this.state.propertyFound));
        }       
    }

我 console.log(newArray) 它给了我正确的值但是 this.state.propertyFound 是空的。或者,我尝试了另一种逻辑。

for(let typeValues in this.state.type){
        for(let locationValues in this.state.location){
            if(this.state.type[typeValues] === true  && this.state.location[locationValues] === true){
                PropertyData.forEach((item,index,arr) => {
                    if(arr[index].propertyType === typeValues && arr[index].location === locationValues){
                        // this.setState({
                        // propertyFound : [...this.state.propertyFound,item]
                        //})
                        let newArray;
                        newArray = this.state.propertyFound.push(item);
                        this.setState({propertyFound : newArray});
                    }
                    
                })

            }
        } 
    }
  

这工作得很好,并给出了正确的结果。任何人都可以解释我正在尝试实施的上述逻辑中的问题吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)