首页 > 解决方案 > 将 prop 传递给 redux

问题描述

我有以下代码:

main.js

submit(v) {
    console.log(v);
    const price = v.get("price");
  }

render() {  
<form onSubmit={handleSubmit(this.submit)}>
    <Field
    name="products"
    categoryId={categoryId}
    component={MyComponent}
    />

    <MySubmitComponent
    confirm={handleSubmit(this.submit)}
    />
  </form>
}

我的组件.js

{this.props.products.map((product, index) => (
<ProductDetails
productId={product.productId}
price={product.price}
/>
))}

ProductsDetails.js

    <Field
    name="price"
    price={price}
    component={PriceText}
    initialValues
    />

    const selector = formValueSelector("products");
    const mapStateToProps = (state, ownProps) => {
      return {
        initialValues: { productId: ownProps.productId },
        productId: selector(state, "productId")
      };
    };
    ProductsDetails= connect(mapStateToProps)(ProductsDetails);

当我更改产品的价格并按提交时,提交函数中的变量值仅包含产品的新价格,而没有它的 productId。我还需要 productId 来通知相应的产品。我想念什么?

标签: reactjsreact-nativereduxreact-reduxredux-form

解决方案


据我所知并使用过redux-form,一个 Field 组件将只有一个在 Store 中注册的值。

因此,您可以将其视为具有不同的多个表单,其中每个表单将具有单独的productIdprice字段。提交表单后 - 您将拥有这两个字段的值。

这是创建多个 Forms 的示例

根据您的用例,它会是这样的:

用法:

{ this.props.products.map(({ productId, price }, index) => (
  <Form form={`product-${productId}`} initialValues={{ productId, price }} />
/>
))}

<Form />

const Form = reduxForm({
  // no need to put form again here as we are sending form props.
})(FormComponent);

<FormComponent />- 只是演示组件:

export const FormComponent = ({ handleSubmit }) => <form onSubmit={handleSubmit}>
  <Field
    name="price"
    component={PriceText}
  />
</form>

推荐阅读