当我在对象数组上调用setState时,无论我做什么都不会粘住。我猜我有一个功能绑定不正确,但是我为此工作了太长时间了。问题区域是SubmitLineItem函数的下一行,所有行旁边都有注释。流程如下:
问题是,我无法获取状态数组来接受新的订单项。我现在已经放弃了。父页面是details.lineitems,操作表是action.sheet。
export default class DetailsLineItems extends React.Component {
constructor(props) {
super(props);
this.state = {
id: props?.route?.data?.id,
user: props?.route?.user,
loading: true,
types: [],
isActionSheetOpen: false,
lineItems: [],
total: 0,
newLineItems: []
};
this.SubmitLineItem = this.SubmitLineItem.bind(this);
this.PostNewLineItems = this.PostNewLineItems.bind(this);
}
CloseActionSheet = () => {
this.setState({ ...this.state, isActionSheetOpen: false })
}
AddLineItemButtonOnPress() {
this.setState({ ...this.state, isActionSheetOpen: true });
}
SubmitLineItem(type, quantity, tax, price) {
if (type === "" || type === 0) return;
if (quantity === 0) return;
if (tax === 0) return;
if (price === 0) return;
let item = this.state.types.find(x => x.id === type);
let newLineItem = {
id: 0,
workorderId: this.state.id,
description: "",
unitPrice: price,
qty: quantity,
tax: tax,
assetId: null,
typeId: item.id,
active: "true",
price: 0
}
var arr = this.state.newLineItems.slice();
console.log("arr", arr); //copies the array, outputs as expected (empty array)
arr.push(newLineItem);
console.log("arr push", arr); //added new item, array is updated as expected (1 object in array)
//this.setState({ newLineItems: arr }, function() { console.log("setState", this.state.newLineItems) }); //does not work, array is empty...
//this.setState({ ...this.state, newLineItems: [ ...this.state.newLineItems, newLineItem ], function () { console.log("setState", this.state.newLineItems) } }); //also does not work, array is empty...
this.setState(prevState => ({ newLineItems: [...prevState.newLineItems, newLineItem] })); //again, doesnt work, array is empty...
}
async PostNewLineItems() {
console.log("newlineitems", this.state.newLineItems) *doesnt work, array shows empty*
}
render() {
return (
<> (whole lotta UI junk)
<ActionSheet types={this.state.types} userType={this.state?.user?.userType} isVisible={this.state.isActionSheetOpen} SubmitLineItem={this.SubmitLineItem} CloseActionSheet={this.CloseActionSheet} />
<Button title={ "Save" }
color={ "#0A1F44" }
style={ styles.bottomButton }
onPress={ this.PostNewLineItems }/>
</>
);
}
}
以下是关于action.sheet的内容。
export default class ActionSheet extends React.Component {
constructor(props) {
super(props);
this.state = {
typeSelect: "",
qty: 0,
tax: 0,
price: 0
};
}
CloseSheetAndSendData() {
this.props.SubmitLineItem(this.state.typeSelect, this.state.qty, this.state.tax, this.state.price);
this.props.CloseActionSheet();
this.setState({ typeSelect: "", qty: 0, tax: 0, price: 0 })
}
render() {
return (
<> (more UI junk)
<Button
onPress={ this.CloseSheetAndSendData.bind(this) }
style={ styles.button }
color="#0A1F44"
title="SUBMIT" />
</View>
</View>
}
</>
);
}
}