如何将 redux 存储传递到动态呈现的 redux-form 组件中? [英] How to pass a redux store into dynamically rendered redux-form component?

查看:50
本文介绍了如何将 redux 存储传递到动态呈现的 redux-form 组件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 redux-form 的 React Redux 应用程序.表单由事件动态呈现.在渲染时,我收到一个错误 未捕获的错误:在Connect(Form(FormCreate))"的上下文或道具中找不到store"

I have a React Redux application, which is using redux-form. Form is render dynamically by event. While it render, I'am getting an error Uncaught Error: Could not find "store" in either the context or props of "Connect(Form(FormCreate))"

为了修复错误,我明确地将一个 store 传递给 Form 组件,如下

To fix error, I explicitly pass a store into Form component, as bellow

render(<FormCreate store={store}/>, document.getElementById('form'))

但是 store 也需要 redux-form 自定义渲染字段.例如

But store also needed by redux-form custom render fiedls. For example

<Field store={store} component={renderField} type="text" name="text" label="Text"/> 

错误消失了,但在我看来这是不好的方法 :) 这就是为什么我问如何更简单地将 redux store 传递到渲染的 redux-form 组件中?

Error was go away, but it seems to me bad approach :) That's why I ask how can I pass a redux store into rendered redux-form component more simply?

PS 如果 Root 元素已经包装在 Provider 中,我可以将呈现的表单组件包装到 Provider 中吗?

PS Can I wrap rendered form component into Provider, if Root element was already wrapped in Provider?

推荐答案

您可以为您的表单使用 reduxForm 装饰器,它将为您解决此问题.在下面的示例中,SimpleForm 是一个由表单组成的 React 组件.这将使来自 Field 组件的数据显示在 Redux 状态中.然而,装饰器只是 es7 的一部分,但在 Typescript 中可用.

You can use the reduxForm decorator for your form which will fix this issue for you. In the example below, SimpleForm is a React component that consists of a form. This will make the data from your Field components to appear in the Redux state. Decorators are however only part of es7 but is available in Typescript.

export default reduxForm({
  form: 'simple' // a unique identifier for this form
})(SimpleForm)

下面的 jsfiddle 展示了如何使用 reduxForm 装饰器 this 的完整示例.

The jsfiddle below shows a full example of how to use the reduxForm decorator this.

https://jsfiddle.net/bmv437/75rh036o/

这篇关于如何将 redux 存储传递到动态呈现的 redux-form 组件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆