问题
I am a redux-form newbie and trying to add two values, 2 fields that look like this:
<Field
className="uk-input"
name="amount1"
component="input"
type="text"
placeholder="dollars"
onChange={this.handleChange}
/>
I use a function that is called in the handleChange event:
handleChange = () => {
console.log("hoer");
this.props.change(
"selectingFormValues",
"totaal",
total(this.props.amount1 + this.props.amount2)
);
};
How can I calculate the total and store the total in the redux-form store?
回答1:
You can use componentDidUpdate
(and remove handleChange
) to calculate the updated sum:
componentDidUpdate() {
const { amount1, amount2 } = this.props;
const tootal = parseFloat(amount1 || 0) + parseFloat(amount2 || 0);
this.props.change("selectingFormValues", "totaal", tootal);
}
and change the total component to be an input
:
<Field className="uk-select" name="totaal" component="input" />
See updated example https://codesandbox.io/s/jl6pwj2r75
Alternatively, you can do the calculation in selector instead than within componentDidUpdate
:
componentDidUpdate() {
this.props.change("selectingFormValues", "totaal", this.props.tootal);
}
and in selector:
const mapStateToProps = state => {
const { amount1, amount2 } = selector(state, "amount1", "amount2");
const tootal = parseFloat(amount1 || 0) + parseFloat(amount2 || 0);
return {
amount1,
amount2,
tootal
};
};
See this second sandbox
来源:https://stackoverflow.com/questions/55707951/how-to-calculate-with-reduxform