如何在React中使用道具自动填充可编辑的redux-form字段?

时间:2017-03-05 18:13:02

标签: forms reactjs react-redux redux-form react-redux-form

我是React的新手,所以我试图在这里展示尽可能多的代码,希望能够解决这个问题!基本上我只想填写表单字段,其中包含我从另一个API获取的对象的属性。该对象存储在autoFill reducer中。例如,我想用autoFill.volumeInfo.title填充输入,用户可以在提交之前更改值,如果需要的话。

我使用了autoFill动作创建器中的mapDispatchtoProps,但是this.props.autoFill仍然在FillForm组件中显示为未定义。我还对如何再次使用道具提交表单感到困惑。谢谢!

我的减速机:

import { AUTO_FILL } from '../actions/index';

export default function(state = null, action) {
  switch(action.type) {
  case AUTO_FILL:
      return action.payload;
  }

  return state;
}

行动创作者:

export const AUTO_FILL = 'AUTO_FILL';

export function autoFill(data) {

  return {
    type: AUTO_FILL,
    payload: data
  }
}

调用自动填充操作创建者:

class SelectBook extends Component {
   render() {

     return (

      ....

     <button
       className="btn btn-primary"
       onClick={() => this.props.autoFill(this.props.result)}>
       Next
     </button>
    );
   }
}

....

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ autoFill }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(SelectBook);

以下是问题所在的实际表格:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import { createBook } from '../actions/index;

class FillForm extends Component {

  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
  }

  onSubmit(props) {
   this.props.createBook(props)
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() { 

    const { fields: { title }, handleSubmit } = this.props;

    return (

       <form {...initialValues} onSubmit={handleSubmit(this.onSubmit.bind(this))}>
          <input type="text" className="form-control" name="title" {...title} />
          <button type="submit">Submit</button>
       </form>
      )
   }

  export default reduxForm({
    form: 'AutoForm',
    fields: ['title']
  },
  state => ({
    initialValues: {
      title: state.autoFill.volumeInfo.title
    }
  }), {createBook})(FillForm)

1 个答案:

答案 0 :(得分:0)

我认为你在实际的表单组件中混合了connectreduxForm装饰器。目前您的代码看起来像这样(我添加的注释):

export default reduxForm({
  // redux form options
  form: 'AutoForm',
  fields: ['title']
},

// is this supposed to be mapStateToProps?
state => ({
  initialValues: {
    title: state.autoFill.volumeInfo.title
  }
}),
/// and is this mapDispatchToProps?
{createBook})(FillForm)

如果是这种情况,那么修复应该像使用connect装饰器一样简单(我还建议将这个连接道具分离到它们自己的变量,以尽量减少这样的混淆):

const mapStateToProps = state => ({
  initialValues: {
    title: state.autoFill.volumeInfo.title
  }
})

const mapDispatchToProps = { createBook }

export default connect(mapStateToProps, mapDispatchToProps)(
  reduxForm({ form: 'AutoForm', fields: ['title'] })(FillForm)
)

希望这有帮助!