How to calculate with reduxform?

自作多情 提交于 2019-12-10 12:15:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!