2016-10-30 34 views
0

データベース内の既存のアイテムを作成または編集できるReactコンポーネントを作成しようとしています。 1つのことを除いてすべてうまくいっています:editルート(異なる動作の同じコンポーネント)からnewルートを呼び出すと、Reactは以前のフォームの状態を保持し、空のデータを持つ新しいフォームを見ることができません。それは私がnewルートをどこか別の場所から呼び出すときにのみ機能します。React Router + Redux Form + Edit/New Component == Fail

可能なルート:

  • /bastions/new - データなし

  • /bastions/:idとコンポーネントを描画する - 既存のデータ

を持つコンポーネントが誰かのために身近な問題ですレンダリング?

(最も関連性の個展に出せるとの)物事をきれいにするだけでいくつかのコード:事前に

感謝。

class BastionForm extends Component { 

    componentWillMount() {  
     if(this.props.bastion.number) {  
      this.props.fetchBastion(this.props.params.number); 
     } 
    } 

    renderField({ input, label, type, meta: { touched, error, warning } }) { 
     return (
      <FormGroup controlId={label} {...validation}> 
       <ControlLabel>{label}</ControlLabel> 
       <FormControl {...input} placeholder={label} type={type} /> 
       <FormControl.Feedback /> 
      </FormGroup> 
     ); 
    } 

    render() { 
     const { handleSubmit, pristine, reset, submitting } = this.props; 

     return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this)) }> 
       <h3>Create a new Bastion</h3> 

       <Field name="sample" type="text" component={this.renderField} /> 

       <ButtonToolbar> 
        <Button bsStyle="primary" disabled={submitting}>Submit</Button> 
       </ButtonToolbar> 
      </form> 
     ); 
    } 
} 

BastionForm = reduxForm({ 
    form: 'BastionForm', 
    enableReinitialize: true 
})(BastionForm); 

BastionForm = connect(
    state => ({ 
     initialValues: state.bastions.bastion 
    }), { fetchBastion } 
)(BastionForm); 

export default BastionForm; 

答えて

0

componentWillMountは、マウントが行われる前に一度だけ呼び出されます。 /bastions/new/bastions/:idは実際に同じルートを参照しているので、/bastions/:idから/bastions/newにパスが変更されたときにBastionFormはマウント解除されません。したがって、存在するデータを表示するか、データなしで表示するかを、BastionForm(アクションのディスパッチ)の状態を変更することによって決定することができます。次に、小道具の変更をcomponentWillReceivePropsで処理します。

+0

サポートにご協力いただき、ありがとうございます。あなたが正しい! componentWillReceivePropsは問題を解決しました。しかし、私は/ bastions /:/ bastions/newの両方が同じルートを参照しているとあなたが言ったことについて何か疑問に思います。最初のものがURLパラメータ(id)を持っていて、任意の文字列(この場合は "new"など)であり、そのためBastionFormはアンマウントされません。しかし、経路を完全に変更しても機能しませんでした。この動作は、reduxと反応ルータの非同期状態と関係がありますか? –

+0

2つのルートが同じコンポーネント(たとえば 'BastionForm')を参照する場合、2つのルートが完全に異なる場合であってもコンポーネントを再作成しません。また、答えが正しい場合は、同じ質問に遭遇した他の人にはそれが明白になるように受け入れてください。 –

+0

さて、私は今それを得る。返信ありがとう! –

関連する問題