重用容器和容器扩展其他容器

时间:2016-05-23 18:50:55

标签: reactjs redux

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函数。是否可以扩展此容器?

1 个答案:

答案 0 :(得分:0)

首先,在我看来,容器是某种组件,所以请遵循这篇文章:https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.jqwffnfup我宁愿谈论容器组件和表示组件。

广告1)我想说我们可以重复使用容器组件以及表示组件 - 这总是取决于我们的代码的结构。例如。容器组件可能有子组件,在屏幕的不同部分可能有所不同,但容器组件正在重复使用。

广告2)如果您只想拥有不同的onSearch功能,我可以考虑通过道具将onSearch回调传递给HomeSearchContainer。这样,您可以重复使用相同的容器,但行为有所不同。 仔细查看您的代码,HomeSearchContainer就没那么多,所以您也可以直接使用SearchForm。如果您需要多个地方的SearchForm,则可能需要将onSearch函数拉出到自己的文件中并重新使用它。但是如果没有看到应用程序的其余部分,这很难判断。所以我想在这里向你提出一些想法,这可能适用于你的代码库,也可能不适用。