删除项目后更新对象数组的状态-React

时间:2019-07-09 06:17:18

标签: javascript reactjs

最初,在我的应用程序中,我从位置数据中检索位置详细信息,并将其放入列表中。现在,如果我从该列表中删除任何项目并尝试保存它,它将显示相同的初始详细信息。我已经尝试了很多方法来更新它,但是我不知道该怎么做。

组件代码:

export class NewLocationPanel extends React.Component{
    constructor(props){
        super(props);
        this.state={
               open:false,
               configuredList:[],
               clearList:[]
        };
       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);
    }

    togglePanel (e){
        this.setState({open : !this.state.open});
    }
    handleRemove(mruCode){
        this.props.removeLocation(mruCode)
     }
    handleClick (mruCode){
      this.props.addLocation(mruCode)
     }
     allLocations (){
       this.props.addAllLocation()
    }
    clearall (){
        this.props.removeAllLocation()
    }

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

    componentDidUpdate(prevProps,prevState){
        if (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);
    }

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


    getLocationData(){
         let saveableLocationlist = [];
         if(this.state.configuredList === null){
             saveableLocationlist = [];
         }
        const locationData = {
            locationDetails : saveableLocationlist
        }
      return locationData;
    }

    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}</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>Locations List</h3><button style={{ display: this.props.location.length === this.props.conLocations.length ? "none" : "block" }} className="allLargeBtn" onClick={()=>{this.allLocations()}}>Add all locations</button></div><hr/>
                             {this.props.location.map((item,index)=>(
                             <div key={index}><div><b>{item.mruCode} - {_labels[item.division]} - {item.country}</b>{!this.props.conLocations.find(item2 => item.mruCode === item2.mruCode)&&(<div className="pull-right jd"><button style={{ display: this.state.configuredList.find(item3=> item.mruCode===item3.mruCode) ? "none" : "block" }} className="call-to-action" onClick={()=>{this.handleClick(item.mruCode)}}>Add Location</button></div>)}<hr/></div></div>))}
                            </div>
                             </div> 
                                  <div className="col-sm-6">
                                  <div className="col-padding">
                                  <div className="pos-div"><h3>Configured Location</h3><button className="allLargeBtn" onClick={()=>this.clearall()}>Remove all location</button></div><hr/>
              <div><table className="table"><thead>{this.state.configuredList.map((locc,index)=><tr key={index}><th><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><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
    };
};

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


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

按照上面的代码,我正在从位置数据中检索详细信息,然后尝试将它们放入配置的列表中。现在,我使用removeConfigLocation删除了项目,并尝试在getLocationData中实现逻辑并将当前值保存到locationData中。但是,它再次显示初始数据。如何更新状态或获取下一个道具?我知道我错过了某个地方的逻辑,但我听不懂。

2 个答案:

答案 0 :(得分:0)

每次执行setState时,都会调用componentDidUpdate。在您的componentDidUpdate

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

您正在使用this.props.locationData并在configLocation中设置状态。我觉得由于您的状态下的configureList正在更新到较早的值。

尝试添加调试器或console.log并测试此逻辑

答案 1 :(得分:0)

首先,您应该在setState回调中进行控制台。

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);
        });
    }

removeConfigLocation(index){
        this.setState({

configuredList:this.props.locationData.locations.locationDetails.filter((__ i)=> i!== index)             },()=> {            //这里您可以添加调度功能来更新所有位置或调用getLocationData           });         }

You haven't called getLocationData from anywhere.

    getLocationData(){
         //Here you should assign to configuredList
         let saveableLocationlist = this.state.configuredList;
         if(this.state.configuredList === null){
             saveableLocationlist = [];
         }
        const locationData = {
            locationDetails : saveableLocationlist
        }
      //Here add dispatch function
      return locationData;
    }

当前正在查看您的代码,我看不到用于设置所有位置数据的调度功能。首先,您必须添加操作和减速器来执行此操作。希望对您有所帮助。