【发布时间】:2020-01-18 08:25:29
【问题描述】:
我想在我的场景中知道:收到道具后,函数在compoentdidupdate 方法中被调用,如果id 相同,则在该方法中求和,但它会继续多次添加值负载。如何解决这个问题。
class Data extends React.PureComponent{
constructor(props){
super(props);
this.state={
total: "";
}
}
componentDidMount() {
this.callFetch();
}
callFetch(){
this.props.dispatch(getData("all"));
this.props.dispatch(newData("new"));
}
componentDidUpdate(){
const { alldata, newdata } = this.props.query;
const obj =[...alldata, ...newdata];
const result=[];
if(obj.length > 0) {
obj.forEach(function (o) {
var existing = result.filter(function (i) { return i.id=== o.id})[0];
if (!existing)
result.push(o);
else
existing.amount+= o.amount;
});
this.setState({total: result})
}
}
render(){
return(
this.state.total.length > 0 ?
this.state.total.map(e=>{
<div>price:{e.amount}</div>
}) : ""
)
}
收到的道具低于,但在输出中收到1200,并且不断增加,
alldata= [{
id: 1,
amount: 200
}, {
id: 2,
amount: 400
}]
newdata= [{
id: "1",
amount: 400
}]
预期输出:
price: 600
price: 400
【问题讨论】:
标签: javascript arrays reactjs redux react-redux