29

redux-formは、react アプリケーションのフォームに redux バインディングを提供するための非常に魅力的なライブラリであり、非常に便利です。残念ながら、ライブラリの独自の例を使用すると、実際には何もバインドできず、非常に不便です。

プロジェクト サイトのサンプル コードを使用しようとしていますが、忠実に再現しようとしても、複数の障害が見つかります。この API のどこを誤解していますか? デモ コードが作成されてから API は変更されましたか? いくつかの重要で明白な還元知識が欠けていますか?

問題 1 : handleSubmit メソッドの署名はhandleSubmit(data). しかし、handleSubmit は現在、送信アクションから React SyntheticEvent のみを受信して​​おり、データは受信していません。onSubmit(実際、この例をそのまま使用すると、2 つの別個のイベントが送信されます。これは、フォーム上とボタン上でアクションが積み上げられているためと思わonClickれます。) そのデータはどこから来ているはずで、なぜ私はそれを渡せなかったのですか?ハンドラーに?

問題 2 :fieldsフォームの親で定義し、フォームの小道具として提供する必要がある重要なオブジェクトがあります。残念ながら、そのfieldsオブジェクトの形状はドキュメントでは説明されておらず、その目的も実際には説明されていません。それは本質的に初期の「状態」オブジェクトですか?実行時にエラーなどに使用する redux-form の単純なオブジェクト コンテナーですか? fieldsのフィールド名にprops を一致させることでエラーを停止するようにしましたconnectReduxFormが、データがバインドされていないため、正しい形状ではないと想定しています。

問題 3onBlur : フィールドは、およびのハンドラーに自動バインドされるonChangeため、ストアが適切に更新されます。それは決して起こっていません。(これは、Redux dev-tools のおかげでわかります。ただし、アクションhandleSubmitのディスパッチに成功しています。initializeこれは、ストア、リデューサー、およびその他の基本的な配管がすべて機能していることを示しています。)

問題 4 : validateContactinit で一度発火しますが、二度と発火しません。

残念ながら、これは単純な Fiddle には複雑すぎますが、レポ全体 (基本的な ReduxStarterApp とこのフォーム POC に加えて)はこちらから入手できます

そして、ここに外側のコンポーネントがあります:

import React       from 'react';
import { connect } from 'react-redux';
import {initialize} from 'redux-form';

import ContactForm from '../components/simple-form/SimpleForm.js';

const mapStateToProps = (state) => ({
  counter : state.counter
});
export class HomeView extends React.Component {
  static propTypes = {
    dispatch : React.PropTypes.func.isRequired,
    counter  : React.PropTypes.number
  }

  constructor () {
    super();
  }
  handleSubmit(event, data) {
    event.preventDefault();
    console.log(event); // this should be the data, but is an event
    console.log(data); // no data here, either...
    console.log('Submission received!', data);
    this.props.dispatch(initialize('contact', {})); // clear form: THIS works
    return false;
  }

  _increment () {
    this.props.dispatch({ type : 'COUNTER_INCREMENT' });
  }


  render () {
    const fields = {
      name: '',
      address: '',
      phone: ''
    };

    return (
      <div className='container text-center'>
        <h1>Welcome to the React Redux Starter Kit</h1>
        <h2>Sample Counter: {this.props.counter}</h2>
        <button className='btn btn-default'
                onClick={::this._increment}>
          Increment
        </button>
        <ContactForm handleSubmit={this.handleSubmit.bind(this)} fields={fields} />
      </div>
    );
  }
}

export default connect(mapStateToProps)(HomeView);

内部フォーム コンポーネント:

import React, {Component, PropTypes} from 'react';
import {connectReduxForm} from 'redux-form';

function validateContact(data) {
  console.log("validating");
  console.log(data);
  const errors = {};
  if (!data.name) {
    errors.name = 'Required';
  }
  if (data.address && data.address.length > 50) {
    errors.address = 'Must be fewer than 50 characters';
  }
  if (!data.phone) {
    errors.phone = 'Required';
  } else if (!/\d{3}-\d{3}-\d{4}/.test(data.phone)) {
    errors.phone = 'Phone must match the form "999-999-9999"';
  }
  return errors;
}

class ContactForm extends Component {
  static propTypes = {
    fields: PropTypes.object.isRequired,
    handleSubmit: PropTypes.func.isRequired
  }

  render() {
    const { fields: {name, address, phone}, handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit}>
        <label>Name</label>
        <input type="text" {...name}/>     {/* will pass value, onBlur and onChange */}
        {name.error && name.touched && <div>{name.error}</div>}

        <label>Address</label>
        <input type="text" {...address}/>  {/* will pass value, onBlur and onChange*/}
        {address.error && address.touched && <div>{address.error}</div>}

        <label>Phone</label>
        <input type="text" {...phone}/>    {/* will pass value, onBlur and onChange */}
        {phone.error && phone.touched && <div>{phone.error}</div>}

        <button type='submit'>Submit</button>
      </form>
    );
  }
}

// apply connectReduxForm() and include synchronous validation
ContactForm = connectReduxForm({
  form: 'contact',                      // the name of your form and the key to
                                        // where your form's state will be mounted
  fields: ['name', 'address', 'phone'], // a list of all your fields in your form
  validate: validateContact             // a synchronous validation function
})(ContactForm);

// export the wrapped component
export default ContactForm;
4

2 に答える 2

23

connectReduxFormfieldsとpropsの受け渡しを処理する別のコンポーネントでコンポーネントをラップしますが、handleSubmitそれらを自分で渡すことでそれらを吹き飛ばしています。

代わりにこれを試してください(小道具の名前を に変更しましたonSubmit):

<ContactForm onSubmit={this.handleSubmit.bind(this)}/>

ContactForm独自の送信ハンドラーをhandleSubmitredux-form によって提供される関数に渡します。

<form onSubmit={handleSubmit(this.props.onSubmit)}>

React 開発者ツールを使用して、何が起こっているかをよりよく把握することをお勧めします。 README に記載されているように、redux-form がコンポーネントをラップし、大量の props を渡す方法を確認できます。

React 開発者ツールでの redux-form コンポジション

于 2015-10-15T08:14:37.553 に答える