在Redux表单中获取父道具表单子

时间:2018-02-28 15:31:45

标签: javascript reactjs redux redux-form

React Newbee这里使用react redux和redux-form

我想使用App.jsForm.js检索到的数据目前我正在{this.props.data}传递给<Form />我无法查看或访问App.js道具在<Form />组件中,我可以看到reduxForm道具,如何在this.props.data内访问<Form />

我有一个用于获取用户数据的组件:

App.js

import React, { Component } from "react";

import { connect } from "react-redux";

import * as actions from "../actions";

import Form from "./Form";

class Questions extends Component {
    componentDidMount() {
        this.props.fetchQuestion();
    }
    render() {
        return <Form formData={this.props.data} />;
    }
}
function mapStateToProps({ data }) {
    return { data };
}
export default connect(mapStateToProps, actions)(Questions);

Form.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { Field, FieldArray, reduxForm } from "redux-form";
import * as actions from "../actions";

class renderForm extends Component {
  renderField({ input, label, type, meta: { touched, error } }) {
    return (
      <div>
        <label>{label}</label>
        <div>
          <input {...input} type={type} placeholder={label} />
          {touched && error && <span>{error}</span>}
        </div>
      </div>
    );
  }
  render() {
    const { handleSubmit, pristine, reset, submitting } = this.props;

    return (
      <form onSubmit={handleSubmit}>
        <Field
          name="clubName"
          type="text"
          component={this.renderField}
          label="Club Name"
        />
        <FieldArray name="questions" component={this.renderQuestion} />
        <div>
        </div>
      </form>
    );
  }
}

function mapStateToProps({ data }) {
  return { data };
}

export default reduxForm({
  form: "fieldArrays"
})(connect(mapStateToProps, { actions })(FieldArraysForm));

2 个答案:

答案 0 :(得分:0)

在这种情况下,您不需要将子组件(form.js)连接到redux,因为您从父组件传递道具。

当你mapSateToProps()覆盖this.props.data的价值时。

而不是

export default reduxForm({
  form: "fieldArrays"
})(connect(mapStateToProps, { actions })(FieldArraysForm));

尝试

export default renderForm

编辑:

此外,我认为您应该导出renderForm而不是reduxForm

答案 1 :(得分:0)

在您的情况下,您应该只使用reduxForm HOC而不连接到redux(connect()包装器):

export default reduxForm({
  form: "fieldArrays"
})(renderForm);

在表单中,您可以使用this.props.formData;

访问来自父级的数据