【发布时间】:2019-06-22 19:59:03
【问题描述】:
我正在尝试更新这些值,但无论何时我console.log 总是0,即使条件为真。
import React, { Component } from "react";
interface orderInformation {
customer: number;
picklePrice: number;
breadPrice: number;
}
interface ComponentState {
customer: number;
picklePrice: number;
breadPrice: number;
error: string;
finalPickleCost: number;
finalBreadCost: number;
pickleCounter: number;
breadCounter: number;
}
export default class pickleSandwich extends Component<
orderInformation,
ComponentState
> {
constructor(props: orderInformation) {
super(props);
//initializing variables to undefined
this.state = {
customer: 0,
picklePrice: 0,
breadPrice: 0,
finalBreadCost: 0,
finalPickleCost: 0,
pickleCounter: 0,
breadCounter: 0,
error: ""
};
this.handleChange = this.handleChange.bind(this);
}
//Get information for the user
getInfo = orderInformation => {
orderInformation.preventDefault();
const { customer, picklePrice, breadPrice } = this.state;
console.log("customer", customer);
console.log("pickle", picklePrice);
console.log("bread", breadPrice);
if (customer > 0) {
for (var i = 0; i < customer; i++) {
if (i % 3 === 0) {
this.setState({
pickleCounter: this.state.pickleCounter + 2,
breadCounter: this.state.breadCounter + 3
});
} else {
this.setState({
pickleCounter: this.state.pickleCounter + 1,
breadCounter: this.state.breadCounter + 2
});
}
}
} else {
this.setState({
error: "Please enter amount of customer"
});
}
console.log("pickle Counter", this.state.pickleCounter);
console.log("breadCounter", this.state.breadCounter);
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value } as any);
};
render() {
// const { customer, finalPickleCost, finalBreadCost } = this.state;
return (
<form onSubmit={this.getInfo}>
<p>Get the information of the order!</p>
<input
type="text"
id="customer"
value={this.state.customer}
placeholder="Amount of Customers"
name="customer"
onChange={this.handleChange}
required
/>
<input
type="text"
id="picklePrice"
placeholder="Price of Pickle"
value={this.state.picklePrice}
name="picklePrice"
onChange={this.handleChange}
required
/>
<input
type="text"
id="breadBrice"
placeholder="Price of Bread"
value={this.state.breadPrice}
name="breadPrice"
onChange={this.handleChange}
required
/>
<button type="submit" onClick={this.getInfo}>
Get Information{" "}
</button>
</form>
);
}
}
我希望它更新值,以便计算最终成本。
【问题讨论】:
标签: reactjs