在Redux表单中获取父级道具

问题描述 投票:1回答:2

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

我想使用App.js内部Form.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));
javascript reactjs redux redux-form
2个回答
0
投票

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

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

在您的表单中,您可以使用this.props.formData从父级访问数据;


0
投票

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

当你mapSateToProps()你压倒this.props.data的价值。

代替

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

尝试

export default renderForm

编辑:

此外,我认为你应该出口renderForm而不是reduxForm

© www.soinside.com 2019 - 2024. All rights reserved.