根据Redux中的ID将对象添加到数组

时间:2019-06-16 20:58:52

标签: javascript reactjs redux react-redux

我有一个位置数据,例如(例如:[{country:“ US”,area:“ virginia”},{country:“ AUSTRALIA”,area:“ sydney”},{country:“ INDIA”,area :“” bangalore“}]。我想通过单击添加按钮将每个位置添加到一个数组。在UI中,我已获取位置数据并显示了这些数据。在通过单击相邻的添加按钮添加任何特定位置的同时,第一个位置正在获取每次将第一个位置对象添加到该数组时。如何基于特定的按钮单击添加位置(例如,如果我单击“ INDIA”位置的按钮,则“ INDIA”位置对象只会添加到数组。

我已经为添加操作创建了动作和减速器。它只是添加的第一项。

actioncreator.js

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

reducer.js

case 'ADD_LOCATION':
        let addedlocation = state.location.find(obj=>obj.id===action.id)
               return{
                   ...state,
                conLocations: [...state.conLocations,addedlocation]
               }

conLocations是我必须添加位置对象的数组。

添加按钮UI部分:

<div className="col-padding"><h3>Locations List</h3><hR/>
                             {this.props.location.map(loc=>(<div className="jd" key={loc.id}>
                             <span><strong>{loc.mruCode} - {loc.division} - {loc.country} | {loc.currency} | {loc.uom}</strong></span><br/><button className="call-to-action"onClick={(id)=>{this.handleClick(loc.id)}}>Add Location</button><hR/></div>))}
                            </div>

连接到componenet代码:

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

const mapDispatchToProps = (dispatch) => {
    return{
        loadData:()=>{dispatch(loadData())},
        addLocation:(id)=>{dispatch(addLocation(id))}
    }
}

我对我的减速器功能有疑问。它会根据其ID添加第一项,但下次状态不会更新。因此它再次添加了第一项。解决方法

1 个答案:

答案 0 :(得分:1)

您的数据

const location = [
{mruCode: "7300", country: "CA", countryText: "Canada", division: "WORLDWIDE_AGRICULTURAL",…},
{mruCode: "1700", country: "US", countryText: "United States", division: "WORLDWIDE_INDUSTRIAL",…}
]

我认为mruCode是主键。如果其他键是主键,只需更改为该键即可。

在按钮上

onClick={()=>{this.props.addLocation(loc.mruCode)}

mapDispatchToProps

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

动作

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

减速器

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

如果您添加所有位置

动作

export const addAllLocation = () => ({
    type : 'ADD_ALL_LOCATION' // If you use type variable, please replace this
})

减速器

case 'ADD_ALL_LOCATION':
   return {
      ...state,
      conLocations: [...state.location]
   }