【发布时间】:2018-09-24 02:23:53
【问题描述】:
我需要两个具有相同功能的组件,但我想将不同的状态属性映射到道具。我如何让它保持干燥(不仅仅是两个独立的组件,代码几乎相同)?以下是其中一个组件的简化版本:
import React, { Component, PropTypes} from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
class MyComponent extends Component{
constructor(props) {
super(props);
}
componentWillReceiveProps(nextProps){
}
render (){
return (
<div className="">
<div>
{this.props.someDate}
</div>
</div>
)
}
}
function mapStateToProps(state){
return {
someData: state.publications.someData
}
}
export default connect( mapStateToProps, {})(MyComponent)
其他组件完全一样,但是 mapStateToProps 应该是这样的:
function mapStateToProps(state){
return {
someData: state.articles.someData
}
}
【问题讨论】:
-
我也会对此非常感兴趣!
-
为什么不简单地导出通过将
connect应用到每个mapStateToProps和MyComponent而创建的两个组件? -
你能详细说明一下吗?这一切都在一个文件中吗?
标签: react-redux