我将React 16.5与subpub lib一起使用。
componentDidMount() {
that = this;
mystate = this.state.OrderItems;
PubSub.subscribe(this.props.topic, this.addData);
}
addData(msg, data) {
for (let i of data) {
console.log(i);
console.log(mystate);
let exist_item = mystate.filter(item => item["product_id"] == i["id"]);
console.log(exist_item);
if (exist_item.length >= 1) {
exist_item[0]["amount"] += 1;
} else {
let tmp = {
"id": v4(),
"name": i["name"],
"amount": 1,
"item_price": i["price"],
"product_id": i["id"]
};
console.log(tmp);
mystate.push(tmp);
console.log(mystate);
}
}
that.setState({
OrderItems: mystate
}); ////1.here I change update the state and rerend
}
componentDidUpdate() {
that = this; ///2.odd thing happens here
mystate = this.state.OrderItems;
console.log(this.state.OrderItems);///here I get []
console.log(mystate); ///here I get []
}
我得到的componentDidUpdate()函数:
Card.js:65 []
Card.js:66 []
我已经更新了数组mystate,但是当我检查componnentDidUpdate()时,那里有空字符串。
ps:我之所以不会像PubSub.subscribe(this.props.topic, this.addData.bind(this));
那样进行绑定,是因为绑定时发生了巨大的内部错误