我有以下代码:
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>
}
MyComponent.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);
当我更改产品的价格并按Submit时,submit函数中的变量值仅包含产品的新价格,而不包含productId 。我还需要productId来通知适当的产品。我想念什么?
答案 0 :(得分:0)
据我所知并使用过redux-form
,一个字段组件在商店中只会注册一个值。
因此,您可以将其视为具有不同的多个表单,其中每个表单将具有单独的productId
和price
字段。提交表单后-您将拥有两个字段的值。
Here's en example of creating multiple 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>
答案 1 :(得分:0)
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
activeIndex: 0
};
this.submit = this.submit.bind(this);
this.goForward= this.goForward.bind(this);
}
submit(values) {
console.log(values);
}
goForward() {
let index = this.state.activeIndex;
let productsSize = products.length - 1;
if (index === productsSize) {
index = -1;
}
++index;
this.setState({
activeIndex: index
});
}
render() {
<form onSubmit={handleSubmit(this.submit)} name="edit">
{this.props.products.map((product, index) => (
<ProductDetails
productId={product.productId}
price={product.price}
/>
))}
</form>
}
let MyProductComponent = reduxForm({ form: "edit" })(
MyComponent
);
const mapStateToProps = (state, ownProps) => {
console.log(formValueSelector("edit")(
state,
"activeIndex");
return {
initialValues: {
productId: formValueSelector("edit")(
state,
"activeIndex"
)
}
};
};
MyProductComponent = withRouter(
connect(mapStateToProps)(toJS(MyProductComponent))
);