如何从动态生成的列表中更新商品状态?我有项目清单。当您单击其中一项时,它会进行api调用。我已经使用了react-redux的状态管理。所以我只想显示基于api的加载状态和完成状态。我尝试从redux更新状态,但是将其应用于所有组件。当我单击每个项目时,所有项目都会更新。有人可以帮我吗?
handleAddToBasket(event, selectedCase, index) {
//get the basket items. if the selected code is already in basket do not add
//get the key value from basket and compare
let isCaseCodeRepeated = false;
if(this.props.basket.items.length) {
this.props.basket.items.map((item, index) => {
if (item.caseCode === selectedCase.caseCode) {
event.currentTarget.value = 'Already Added!';
isCaseCodeRepeated = true;
return false;
}
})
}
if (isCaseCodeRepeated) {
return false;
} else {
var caseCode = selectedCase.caseCode;
this.setState({
index: index
});
this.props.getCaseByCaseCode(selectedCase.caseCode, index);
}
}
static getDerivedStateFromProps(props, state) {
return (props.case && {isLoading: props.case.isLoading})
}
render() {
const caseContents = this.props.campaign && this.props.campaign.success && this.props.campaign.campaign.campaignContents.map((content, index) => {
return (
<div key={index} className="case-component">
<p className="case-title">{ content.name } | { content.caseCode }</p>
<input type="button" className="button button-secondary" value={((this.props.case.selectedCaseCode === this.state.index) && this.state.isLoading) ? "loading" : "Add to basket" } onClick={(e) => {this.handleAddToBasket(e, content, index)}}/>
</div>
)
})
return (
<div className="container">
<div className="flex-row flex-wrap">
{ caseContents }
</div>
</div>
);
}
CaseReducer
export default (state = {}, action = {}) => {
switch(action.type) {
case GET_CASE_BY_CASE_CODE_LOADING :
return {...state, isLoading: true, selectedCaseCode: action.payload }
case GET_CASE_BY_CASE_CODE_SUCCESS :
return { ...state, caseByCaseCode:action.payload, isLoading: false }
case GET_CASE_BY_CASE_CODE_ERROR :
return { ...state, caseByCaseCode:action.payload, isLoading: false }
default :
return state
}
}
谢谢。