2017-10-02 2 views
1

私は、ReactJS/Reduxを使用して不要な依存性注入の過剰使用をリファクタリングすることを任されています。react-reduxのconnect()をオーバーライドするためにpropsを書くことができますか?

<CardContainer 
    addCountry={actions.addCountry} 
    addDateRange={actions.addDateRangeFilter} 
    addDistributor={actions.addDistributor} 
    addListFilterItem={actions.addListFilterItem} 
    addListFilterWithOneItem={actions.addListFilterWithOneItem} 
    {/* ...other props removed for brevity */} 
/> 

これらの小道具は、すべてのコードベース上に複数の場所で繰り返される(このような複数のコンポーネントのための):

依存性はそれほどようJSXマークアップ内の小道具を使用して注入されます。

export default connect(undefined, dispatch => ({ 
    actions: bindActionCreators(MyActions, dispatch), 
}))(class DistributorFilterPaneCards extends Component { 
    static propTypes = { 
    addCountry: PropTypes.func, 
    addDateRange: PropTypes.func, 
    addDistributor: PropTypes.func, 
    addListFilterItem: PropTypes.func, 
    addListFilterWithOneItem: PropTypes.func, 

:そうのような(react-redux NPMパッケージから)

私は(Connectを介して行くとCardContainerクラスに小道具として、これらの関数を渡す必要がなくなり、その場所にを使用しています)しかし、私が見つけたのは非常に稀に小道具があります。addCountryたとえば、他のすべての機能とは異なる機能が渡されています。

は基本的に、私は静的defaultPropsオブジェクトのような)(接続仕事を持っていると思います。私は、コードベース全体ではなく、必要に応じてリファクタリングできるように、connect()をJSXで渡された小道具でオーバーライドすることができますか?

答えて

0

ではなく、グローバルデフォルトの動作を変更し、私は、defaultPropsオブジェクトを作成し、あなたがそれを必要な場所というのインポートなどのようにそれを適用し推薦する:

default_props.js

module.exports = { 
    addCountry: actions.addCountry, 
    addDateRange: actions.addDateRangeFilter, 
    addDistributor: actions.addDistributor, 
    addListFilterItem: actions.addListFilterItem, 
    addListFilterWithOneItem: actions.addListFilterWithOneItem 
}; 

some react component file

var defaultProps = require('default_props.js'); 

... 

<CardContainer {...defaultProps} /> 

defaultPropsは、別の引数としてオプションの引数をとる関数を作ることができます例:

var defaultProps = (useCase) { 
    useCase = useCase || 'standard'; 

    var props = {}; 

    if (useCase === 'weird-component') { 
    //don't include some default property 
    } 

    return props; 
}; 

便利な読書:https://zhenyong.github.io/react/docs/jsx-spread.html

関連する問題