如何使选择器在Redux形式的应用程序中工作?

时间:2019-04-20 07:59:55

标签: reactjs redux selector redux-form

我是一名新手,正在尝试在Redux形式的应用程序中使用选择器。这是一个简化的示例(原始形式包含数十个计算和字段)。它从表格中提取2笔金额并返回:

import { createSelector } from "reselect";
import { sum } from "../calculations";

const sumAmounts = state =>{
    debugger
    if (!state) return;

    if (!state.amount1 || !state.amount2)
  return  sum(state.amount1,state.amount2);
};
export default createSelector(
    sumAmounts
);

运行表单时,它不会调用sumAmounts:

import React from "react";
import { Field, reduxForm, formValueSelector } from "redux-form";
import { connect } from "react-redux";
import sumAmounts from "../selectors/sumSelector";

export class FormContainer extends React.Component {
  render() {
    return (
      <form>
        <Field
          name="amount1"
          type="number"
          component="input"
          label="Amount 1"
        />
        <Field
          name="amount2"
          type="number"
          component="input"
          label="Amount 1"
        />
        <Field
          name="amount3"
          type="number"
          component="input"
          label="Amount 3"
        />
        <Field
          name="amount4"
          type="number"
          component="input"
          label="Amount 4"
        />
        <Field
          name="amount4"
          type="number"
          component="label"
          label={this.props.sum}
        />
      </form>
    );
  }
}

FormContainer = reduxForm({
  form: "myForm" // a unique identifier for this form
})(FormContainer);

const selector = formValueSelector("myForm");

FormContainer = connect(state => {
  const amount1 = selector(state, "amount1");
  const amount2 = selector(state, "amount2");
  const sum = sumAmounts(amount1, amount2);
  return { amount1, amount2, sum };
})(FormContainer);

export default FormContainer;

如何确保它被调用?

1 个答案:

答案 0 :(得分:1)

您的sumAmounts不是选择器,您正在使用2个参数(sumAmounts(amount1, amount2))调用它,但是它只有一个参数state

在您的mapstatetoprops中,您已经在提取需要计算总和的状态道具,即amount1amount2,那么为什么不在那里计算总和而不是通过其他选择器呢?

  const amount1 = selector(state, "amount1");
  const amount2 = selector(state, "amount2");
  const sum = +amount1 + +amount2;
  console.log("map state to props " , amount1, amount2, sum);
  return { amount1, amount2, sum };