如何在React中清空对象数组

时间:2019-07-17 05:33:09

标签: javascript reactjs

我有一个包含对象列表的数组。通过单击删除所有项目按钮,该数组将为空。但是,动作事件不适用于该按钮,并且项目仍然存在。

我尝试将length设置为0,但是它不起作用。这是我的代码

组件代码:

export class NewLocationPanel extends React.Component{
    constructor(props){
        super(props);
        this.state={
               open:false,
               configuredList:[]
        };
       this.configLocation = this.configLocation.bind(this);
        this.togglePanel = this.togglePanel.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.allLocations = this.allLocations.bind(this);
        this.clearall = this.clearall.bind(this);
        this.getLocationData = this.getLocationData.bind(this);
        this.handleRemove = this.handleRemove.bind(this);
        this.removeConfigLocation = this.removeConfigLocation.bind(this);
        this.removeLocationAll = this.removeLocationAll.bind(this);
        this.handleChecklocation = this.handleChecklocation.bind(this);
        this.handleCheckedAdded = this.handleCheckedAdded.bind(this);
    }

    togglePanel (e){
        this.setState({open : !this.state.open});
    }

//other action code


    componentDidMount() {
        this.props.loadData();
        if(this.props.locationData !=null && this.props.locationData!= undefined){
            this.configLocation(this.props.locationData);
        }
      }

    componentDidUpdate(prevProps,prevState){
        if ((prevProps.jobId != this.props.jobId || prevProps.locationData != this.props.locationData)){ 
            this.configLocation(this.props.locationData);
        }
    }

    configLocation(locationData){
        let configuredList =[];
        if(locationData.locations.locationDetails != null && locationData.locations.locationDetails !=undefined ){
            locationData.locations.locationDetails.map(item=>{
                 let listitem ={...item};
                 configuredList.push(listitem);
            });
        }
        this.setState({configuredList},()=>{
            console.log(this.state.configuredList);
        }); 
    }

    removeLocationAll(){
        this.state.configuredList.length = 0;
    }

    removeConfigLocation(index){
        this.setState({
            configuredList:this.props.locationData.locations.locationDetails.filter((_,i)=>i!==index)
        },()=>{
            console.log(this.state.configuredList);
        });

    }


    //other codes

    render(){
        //const{configuredList} = this.state;
        const _labels = store.getLabels();
        let collapsedToggle = this.props.open ? 'collapsed' : ''
        return(
            <div className="panel panel-default">
            <div className="panel-heading" onClick={(e)=>this.togglePanel(e)}>
              <div className="row">
              <div className="col-xs-12 col-sm-8 col-md-6 col-lg-6 panelHeadingLabel">
                     <span>{this.props.title}</span>
                     </div>
                        <div className="pull-right">
                        <span className="defaultHeaderTextColor">{this.state.configuredList.map((loc,index)=><span key={index}>{loc.mruCode} - {_labels[loc.division]} - {loc.country}{index < this.state.configuredList.length-1 ?',\u00A0' : ''}</span>)}
                           <span onClick={(e)=>this.togglePanel(e)} className={this.state.open ? "collapse-chevronn" : "collapse-chevron"} aria-hidden="true"></span>
                   </span>
                    </div>
                </div>
           </div>
              {this.state.open?(
                        <div className="panel-body">
                             <div className="row grid-divider">
                                  <div className="col-sm-6">
                                  <div className="col-padding">
                                  <div className="pos-div"><h3>Configured Location</h3><button className="submitSmallBtn2">Delete Checked</button><button className="allLargeBtn" onClick={()=>this.removeLocationAll()}>Remove all location</button></div><hr/>
              <div><table className="table"><thead>{this.state.configuredList.map((locc,index)=><tr key={index}><th><input type="checkbox"/><label></label></th><th className="text-left"><b>{locc.mruCode} - {_labels[locc.division]} - {locc.country}</b></th><th className="text-right"><img alt="DeleteIcon" onClick={()=>{this.removeConfigLocation(index)}} className="deleteIconStyle" src="img/delete_large_active.png" /></th></tr>)}</thead><tbody>
                        {this.props.conLocations.map((loct,index)=><tr key={index}>
                           <td><input type="checkbox"/><label></label></td>
                           <td><b>{loct.mruCode} - {_labels[loct.division]} - {loct.country}</b></td>
                           <td className="text-right"><img alt="DeleteIcon" onClick={()=>this.handleRemove(loct.mruCode)}className="deleteIconStyle" src="img/delete_large_active.png" /></td>
                        </tr>
                        )}
                    </tbody></table></div>

                                   </div>
                                  </div>
                                  </div> 
                    </div>):null}
            </div>

        );
    }
}

const mapStateToProps = state =>{
    return{
        location:state.locationRed.location,
        conLocations:state.locationRed.conLocations,
        isChecked:state.locationRed.isChecked
    };
};

const mapDispatchToProps = (dispatch) => {
    return{
        loadData:()=>{dispatch(loadData())},
        addLocation:(mruCode)=>{dispatch(addLocation(mruCode))},
        addAllLocation:() =>{dispatch(addAllLocation())},
        removeLocation: (mruCode)=>{dispatch(removeLocation(mruCode))},
        removeAllLocation: () =>{dispatch(removeAllLocation())},
        checkboxState:(mruCode)=>{dispatch(checkboxState(mruCode))},
        checkedLocation:()=>{dispatch(checkedLocation())}
    }
}


export default connect(mapStateToProps,mapDispatchToProps,null,{withRef:true})(NewLocationPanel);

所以,我无法理解为什么此'removeLocatonAll()'事件不起作用

4 个答案:

答案 0 :(得分:2)

尝试一下

removeLocationAll(){
     this.setState({configuredList:[]});
}

答案 1 :(得分:2)

在删除项目时,需要将configureList的setState设置为空,以便调用重新渲染并反映更改,而不是直接改变状态

removeLocationAll(){
    this.setState({configuredList: []});
}

答案 2 :(得分:2)

在函数removeLocationAll中,您正在直接更改状态,这是错误的。如果要更改状态,则必须仅使用setState方法。

removeLocationAll(){
  this.setState({configuredList:[]});
}

这是处理状态的正确方法。永远不要尝试直接更改状态,否则React将无法在您的代码中找到状态更改。

答案 3 :(得分:2)

第一件事,永远不要那样更新状态对象! 您应该始终使用this.setState({...})

回答,您需要使用this.setState({configuredList: []});