gpt4 book ai didi

reactjs - 我应该如何将 reduxForm 的子组件连接到 redux 状态?

转载 作者:行者123 更新时间:2023-12-03 14:21:25 24 4
gpt4 key购买 nike

我有一个相当复杂的多级深层/嵌套形式,使用 reduxForm() 连接到 React/Redux 。由于表单非常大,我已将其部分分解为子组件。其中一些组件需要访问 Redux 状态,因此需要通过 props 传递连接或进行 connect()ed。然而,当我使用普通的 Redux connect() 函数连接子组件时,无法编辑其中的 redux-form 字段。因此,我尝试使用 reduxForm() 来连接子组件和父组件,这感觉不对,但似乎有效。

但是我现在发现一些功能(例如 removeField())在连接的子组件中不起作用 - 例如child_form.removeField(index) 删除所有 child_form,而不仅仅是与索引匹配的那个。

reduxForm() 组件的子组件连接到 redux 状态的正确/最佳实践方法是什么?使用 props 通过层次结构传递所有内容很快就会变得笨拙......

最佳答案

However I'm now discovering that some functionality like removeField() isn't working in the connected subcomponents -- e.g. child_form.removeField(index) removes all the child_forms, not just the one matching the index.

有两种方法可以解决这个问题:

  1. 使用 Action 创建器

    removeField 方法包装了 removeArrayValue 操作创建者。您可以调度此操作来删除表单中的条目。

    // Removes the 4th row
    dispatch(removeArrayValue("myform", "myarrayfield", 3))
  2. 使用插件

    在reducer插件中,您可以拦截操作并触发表单状态的修改。如果您调度一个操作,您可以拦截它并更新字段数组。

Passing everything through the hierarchy using props is going to become unwieldy very quickly...

我已经看到了几种解决方法。

  1. 使用相同的表单名称创建多个表单。 Redux Form 内部会将它们合并,以便您的存储包含同一对象中每个子表单的数据。

  2. 使用 connect 连接子表单并使用操作创建器来操作状态。

  3. 将表单分成更小的部分并传递字段这是我最喜欢的解决方案。我们在我们的应用程序中成功地做到了这一点(在一百多个表格上!)。

    const MainForm = reduxForm({
    form: "main",
    fields: [
    SubForm1.fields,
    SubForm2.fields,
    SubForm3.fields,
    ]
    })(
    props => (
    <form onSubmit={props.handleSubmit}>
    <SubForm1 fields={props.fields} />
    <SubForm2 fields={props.fields} />
    <SubForm3 fields={props.fields} />
    <button type="submit">Send</button>
    </form>
    )
    )

    const SubForm1 = ({fields}) => (
    <div>
    <TextField {...fields.foo} />
    <TextField {...fields.bar} />
    </div>
    )

    SubForm1.fields = ["foo", "bar"]

关于reactjs - 我应该如何将 reduxForm 的子组件连接到 redux 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37692225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com