我有一个位置数据,例如(例如:[{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添加第一项,但下次状态不会更新。因此它再次添加了第一项。解决方法
答案 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)}
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]
}