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

问题描述 投票:0回答:1

我是一个反应新手并试图在我的redux-form应用程序中使用选择器。这是一个简化的示例(原始表单包含数十个计算和字段)。它从表单中获取总计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;

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

reactjs redux selector redux-form
1个回答
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 }; 
© www.soinside.com 2019 - 2024. All rights reserved.