如何让选择器在 redux-form 应用程序中工作?

How to get selector working in redux-form app?

我是一个 React 新手,正在尝试在我的 redux-form 应用程序中使用选择器。这是一个简化的示例(原始表格包含数十个计算和字段)。它从表格中提取 2 个金额,returns 它:

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;

我怎样才能确定它被调用了?

您的 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 };