2017-08-09 4 views
0

私のreact-routerアプリの各ページにあるこの機能を持っています。私の機能をどのようにリファクタリングするのですか?

submitForm(e) { 
    const redirect = this.props.location.query.redirect; 
    const age = this.refs.age.value; 

    const gender = this.refs.gender.value; 

    const ethnicity = this.refs.ethnicity.value; 

    if (!age || !gender || !ethnicity) { 
     this.props.dispatch(
     showError({ 
      type: 'SHOW_MODAL', 
      modalType: 'SHOW_ERROR', 
      modalProps: { 
      onClose: hideModal, 
      text: 'Please complete all fields', 
      }, 
     }) 
    ); 
    } else { 
     this.props.dispatch(addDetails(age, gender, ethnicity)); 
     if (redirect) { 
     this.props.router.push('6'); 
     } else { 
     this.props.router.push('4'); 
     } 
    } 
    } 

私は反応するのが新しいです、これをどのようにして各コンポーネントに小道具として渡すことができますか?各コンポーネントでコードを繰り返すのではなく、

このようなファイルをhelpersに入れることはできますか?

import helpers from './helpers'; 
import './index.css'; 
const store = configureStore(); 
console.log({ store }); 
render(
    <Provider store={store}> 
     <Router history={browserHistory} routes={routes} {...helpers} /> 
    </Provider>, 
    document.getElementById('root') 
+0

既にヘルパーがいれば、それを 'export submitForm'の中に入れてください。それから 'import {submitForm} 'を'。/ helpers'' –

答えて

0

はい。

あなたは機能(export default submitForm(e)...)をエクスポートし、this.props.submitFormを呼び出すことができます<Router ... sumbmitForm={helpers} />

あなたの子コンポーネントとして、コンポーネントにそれを渡すためにあなたのヘルパーモジュールが必要になります()。

また、チェーン内の各子コンポーネントに渡す必要があります。

+0

にして、どういうふうに' thunk'を使うことができますか? – Bomber

+0

あなたが状態管理のためにreduxを使用しているなら、上の関数を実行してあなたのコンポーネントからそれをディスパッチするアクションを作成することができます。サンクは、非同期アクションをディスパッチできるミドルウェアです。あなたの質問のあなたの機能は非同期であるとは思われないので、サンクの使用を正当化するものではありません – hairmot

関連する問題