2016-11-09 7 views
0

react-reduxで必要な定型文を減らすためにcreateScreenというファクトリ関数を作成すると考えました。反応還元ボイラプレートを減らす方法 - 私はComponentFactoryを作成しようとしましたが、反応再現エラーが発生しました

それは次のようになります。

ParentScreenFactory.js何らかの理由で

export default function createScreen(stateActions = []) { 
    class ParentScreen extends React.Component { 

    } 

    function mapStateToProps(state) { 
    return { 
     ...state, 
    }; 
    } 

    function mapDispatchToProps(dispatch) { 
    const creators = Map() 
      .merge(...stateActions) 
      .filter(value => typeof value === 'function') 
      .toObject(); 

    return { 
     actions: bindActionCreators(creators, dispatch), 
     dispatch, 
    }; 
    } 

    return connect(mapStateToProps, mapDispatchToProps)(ParentScreen); 
} 

Child.js

const ParentScreen = createScreen([ 
    routingActions, 
    authActions, 
]); 

class Child extends ParentScreen { 

    constructor(props) { // <-- error on this line 
    super(props); 
    } 

    render() { 
    return (
     <View/> 
    ); 
    } 
} 
export default Child; 

しかし、私はundefined is not an object (evaluating 'context.store')を取得します。 スタックトレース:

Connect(ParentScreen) 
connect.js:129 
_this.store = props.store || context.store;

コードのこの行です。 ここに明白な間違いがありますか? それ以外の定型コードをすべて減らす方法については、他にはありませんか?

ありがとうございます。

+0

あなたのタイトルはあなたの質問とは完全に無関係です。エラーを修正し、最後に「どのように私が定型文を減らすことができますか」を投げる方法について質問します。 –

答えて

2

空の接続された1つ(this is the class you're actually extending)を拡張しようとするのではなく、実際のコンポーネントクラスを操作するとすべてが簡単になります。

コンポーネントを予測可能に動作させたい場合は、コンポーネントを直接接続する必要があります。代わりにファクトリから関数を返すようにしてください。

export default function createScreen(stateActions = []) { 
    return (Component) => { 
    // ... 
    return connect(mapStateToProps, mapDispatchToProps)(Component); 
    }; 
} 

これで、インスタンス化は次のようになります。

class Child extends React.Component { 
    // ... 
} 

const ParentScreen = createScreen([ 
    routingActions, 
    authActions, 
]); 

export default ParentScreen(Child); 

すべてのコンポーネント間でいくつかの動作を共有したい場合は、上位コンポーネントを使用する方がよいでしょう。

function withCommonBehaviour(Component) { 
    return (props) => { 
    let newProps = doSomething(props); 
    return <Component {...newProps} />; 
    }; 
} 

次に、createScreenの機能の中でそれをフックしてください。

// ... 
let CommonComponent = withCommonBehaviour(Component); 
return connect(mapStateToProps, mapDispatchToProps)(CommonComponent); 
+0

実際にはうまく見えますが、親コンポーネントのコンストラクタにも同様のことを実行する方法がありますか? これは私が言いたいことを忘れていたものですが、私はそれが必要です。 – SudoPlz

+0

"親コンポーネント"が何であるか分かりません。 –

+0

[OK]を、私は私の子コンポーネントがいつものようにそれのコンストラクタ内で実行されているいくつかの定型コードが欲しいと言うことができます: クラスの子がReact.Component { コンストラクタ(小道具){/ *ここで何かを行う* /} } 缶を拡張します私はあなたの提案を使って作成した各子供のために何度も繰り返し書くことをスキップしますか?おそらく、その定型コードを 'createScreen'メソッドの中に追加することによって? – SudoPlz

関連する問題