使用redux -react将选中的对象添加到数组中

时间:2019-07-15 14:04:35

标签: javascript reactjs checkbox react-redux

我有一个包含很多物品的位置清单。每个项目都有一个复选框。如果我检查了多个项目,然后单击一个按钮 Add Checked ,它将所有选中的项目添加到另一个列表中。我不明白如何为此编写动作和减速器功能?

我已经成功地在reducer中编写了单项添加按钮功能,并且工作正常。如何对多个复选框值进行操作并将其添加?

添加项的操作代码(按钮功能单个项)

export const addLocation = mruCode =>({
  type: ADD_LOCATION,
  payload:mruCode
});

添加项的缩编代码(按钮功能单个项)

case 'ADD_LOCATION':
         let addedLoc = state.location.find(obj=>(obj.mruCode === action.payload))
               return{
                   ...state,
                   conLocations: [...state.conLocations,addedLoc]
               };

组件代码:

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

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

    removeLocationAll(){
        this.props.locationData.locations.locationDetails.length = 0;
    }

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

    }


    getLocationData(){
         let saveableLocationlist = [];
         if(this.props.conLocations != null && this.state.configuredList !=null){
             const{configuredList} = this.state;
             const{conLocations} = this.props;
                 let totalList = configuredList.push(conLocations);
             saveableLocationlist = totalList;
         }
        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}{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>Locations List</h3><button className="allLargeBtn">Checked items</button><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><input type="checkbox1"/><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.removeLocationAll()}>Remove all location</button></div><hr/>
              <div><table className="table"><thead>{this.state.configuredList.map((locc,index)=><tr key={index}><th><input type="checkbox1"/></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="checkbox1"/></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
    };
};

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

如果我们单击“选中的项目”按钮,它将把所有选中的项目调用到另一个列表中。怎么做?请帮助我进行减速机和多件检查项目的操作。流程将类似于初始列表(位置)->动态选中(多个项目)->选中项目按钮(onClick)->添加结果(conLocation)列表

初始位置列表如下: [{mruCode:“ 7300”,国家/地区:“ AUSTRALIA”,州:“ Queensland”,部门:“ Engineering”,...},...]

Initial phase

1 个答案:

答案 0 :(得分:0)

假设您有一个描述为您的状态的复选框列表,如下所示:

state = {
    checkboxes : [
        {id: 1, checked: false},
        {id: 2, checked: true},
        {id: 3, checked: false},
    ]
}

然后单击您想要将选中的项目添加到减速器中的单击:

const addCheckedToReducer = () =>{
    const checked = this.state.checkboxes.filter(x => x.checked)
    this.props.dispatchItems(checked) //Your action creator
}

动作创建者:

const dispatchItems = items =>({
    type: 'DISPATCH_ITEMS',
    items
})

最后是减速器:

switch(action.type){
    case 'DISPATCH_ITEMS' : return{
        ...state,
        items : this.state.items.concat(action.items).flat()
    }
}