如何将本地状态与redux状态集成在一起

时间:2019-06-28 16:19:40

标签: javascript reactjs redux

有一个jobdetailjson,其中包含特定作业的作业详细信息。现在,我正在实施位置组件。有两个部分。在一部分中,我通过api获取主要位置列表,并使用添加按钮显示该列表。在另一部分中,我正在从jobdetailjson中检索工作位置。现在,将位置从主列表添加到检索列表时出现问题。这两个列表都显示,但是没有串联。因为,从作业detailjson检索我正在使用本地反应状态,但对于主要位置并添加操作,我正在使用全局Redux状态。如何一起执行此操作,以便获得连接列表。

到目前为止,我已经尝试过了。

工作列表组件:(我从这里使用ref回调检索保存的位置)

import React from 'react';
import ReactDOM from 'react-dom';
import LocationPanel from '../panels/NewLocationPanel';

class JobsPanelComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = { 
            jobDetailJson: this.props.jobDetailJson

        };
this.setLocationPanelRef = cRef =>{this.locationPanel = cRef;};

}
componentWillUnmount() {
        this.clearStates();
        this.clearRefs();
        this.clearBindings();
    }
          clearStates() {

        this.state.jobDetailJson = null;
        }
        clearRefs(){
               this.locationPanel = null;
                   }
        clearBindings(){
               this.setLocationPanelRef = null;
                       }
        componentWillMount() {
        this.state.jobDetailJson = this.props.jobDetailJson;
    }

    componentWillReceiveProps(nextProps) {
        this.state.jobDetailJson = nextProps.jobDetailJson;
    }
      render(){
         return(<div className="panel-group" id="jobsPanelGroup">
              <LocationPanel ref={this.setLocationPanelRef} jobDetailJson={this.state.jobDetailJson} versionId={versionId} jobName={jobName} jobId={jobId} isForViewOnly={this.props.isForViewOnly} title="Location"/></div>
              );
         }
}

位置面板组件:(我在其中检索位置详细信息,并且要添加主要位置列表以及检索位置)

export class NewLocationPanel extends React.Component{
    constructor(props){
        super(props);
        this.state={
               open:false,
               conLocations:[]
               //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);
    }
    togglePanel (e){
        this.setState({open : !this.state.open});
    }
    handleClick (mruCode){
      this.props.addLocation(mruCode)
     }
     allLocations (){
       this.props.addAllLocation()
    }
    clearall (){
        this.props.removeAllLocation()
      }

    componentDidMount() {
        this.props.loadData();
      }

    componentDidUpdate(prevProps){
        if ((prevProps.jobId != this.props.jobId || prevProps.jobDetailJson != this.props.jobDetailJson) && this.props.jobDetailJson != undefined) {
            this.configLocation(this.props.jobDetailJson);
        }

    }

    configLocation(jobDetailJson){
        let conLocations = jobDetailJson.locations.locationDetails;
        this.setState({conLocations});
        console.log(conLocations);
    }


    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.conLocations.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 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>{this.state.conLocations.map((locc,index)=><table className="table" key={index}><tbody><tr><td><b>{locc.mruCode} - {_labels[locc.division]} - {locc.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><ConfiguredLocation/></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())},
        removeAllLocation: () =>{dispatch(removeAllLocation())}
    }
}


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

动作js :(获取主要位置列表并添加和删除)

export const loadData = () => {
  return (dispatch) => {
    return axios.get(serviceUrl)
    .then(response=>{
      dispatch(getLocationData(response.data.mruPreferences))
    })
    .catch(error=>{
      throw(error);
    });
  };
};

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


  export const removeLocation = mruCode => ({
      type: REMOVE_LOCATION,
      payload:mruCode
  });

减速器(用于上述动作)

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

现在,问题在于如何将jobdetailsjson集成到redux中。因此,我可以合并该列表。如何解决本地和全球状态问题。

0 个答案:

没有答案