2016-05-23 110 views
0
import React from 'react' 
import { connect } from 'react-redux' 
import { bindActionCreators } from 'redux' 
import { setLocation } from 'redux/modules/filters' 
import SearchForm from 'components/SearchForm/SearchForm' 

type Props = { 
}; 

export class HomeSearchContainer extends React.Component { 
    props: Props; 

    static contextTypes = { 
    router: React.PropTypes.object.isRequired 
    }; 

    constructor(props) { 
    super(props) 

    this.onSearch = this.onSearch.bind(this) 
    } 

    onSearch(address, event) { 
    event.preventDefault() 
    if (address) { 
     this.props.actions.setLocation(address) 
    } 
    this.context.router.push('/browse_items') 
    } 

    render() { 
    return (
     <SearchForm 
     onSearch={this.onSearch} 
     currentLocation={this.props.currentLocation} 
     /> 
    ) 
    } 
} 

const mapStateToProps = (state) => { 
    return { 
    currentLocation: state.filters.location 
    } 
} 
const mapDispatchToProps = (dispatch) => { 
    var actions = { 
    setLocation 
    } 

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

export default connect(
    mapStateToProps, 
    mapDispatchToProps 
)(HomeSearchContainer) 

我有幾個問題來驗證我的理解。重新使用容器和容器擴展其他容器

  1. 我們曾經重複使用過容器嗎?如果我說我們打算重新使用組件而不是容器,我是否正確?
  2. 在上面的代碼中,我想創建另一個不重定向到/browse_items的容器。換句話說,我只是想重寫此容器的onSearch函數。可以擴展這個容器嗎?

回答

0

首先,在我看來,容器是某種組件,因此遵循本文:https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.jqwffnfup我寧願談論容器組件和表示組件。

Ad 1)我會說我們可以重複使用容器組件以及表示組件 - 這總是取決於我們的代碼的結構。例如。一個容器組件可能有子組件,這些組件在屏幕的不同部分可能不同,但容器組件正在被重用。

廣告2)如果你只是想有一個不同的onSearch功能,我可以考慮通過道具回調到HomeSearchContainer。這樣,您可以重新使用相同的容器,但其行爲有所不同。 仔細查看你的代碼,那麼HomeSearchContainer沒有太多的餘地,所以你不妨直接使用SearchForm。如果您需要在多個地方使用SearchForm,則可能需要將onSearch函數拉出到其自己的文件中並重新使用它。但是如果沒有看到其他應用程序,這很難判斷。所以我試圖在這裏提出一些想法,這些想法可能適用於或不適用於您的代碼庫。