首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重用容器和扩展其他容器的容器

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

Stack Overflow用户
提问于 2016-05-23 18:50:55
回答 1查看 976关注 0票数 0
代码语言:javascript
复制
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函数。可以扩展这个容器吗?
EN

回答 1

Stack Overflow用户

发布于 2016-05-24 17:56:59

首先,在我看来,容器是一种特定类型的组件,因此在本文中:abramov/smart-and-dumb-components-7ca2f9a7c7d0#.jqwffnfup,我更愿意讨论容器组件和表示组件。

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37398410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档