How to pass a redux store into dynamically rendere

2019-08-21 12:08发布

问题:

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))"

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

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

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

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

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 Can I wrap rendered form component into Provider, if Root element was already wrapped in Provider?

回答1:

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)

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

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