将其直接连接到这些组件中,或者在父组件中完成,并传递支持。最后一个似乎更理想,您只需创建一个连接实例。你认为如何?
这里有一个例子:
发布于 2016-02-10 09:19:56
这是一个非常基于意见的答案,因为它可能不是最有效的方式,但我肯定更喜欢第二种方式。我认为这里不需要仅仅为了访问分派功能而连接组件。将功能作为支柱传递给您的代码具有更高的可重用性,因为父组件现在具有控制子组件的功能,方法是将功能传递为道具。
我也不会注入完整的分派,但可能只注入已经绑定了mapDispatchToProps的操作。
它看起来像这样(未经测试的代码!):
import * as MenuActionCreators from './MenuActionCreators';
import { bindActionCreators } from 'redux;'
const MenuIcon = ({
onClickAction
}) => (
<IconButton onClick={onClickAction} touch>
<ImageDehaze />
</IconButton>
)
const CreateIcon = ({
onClickAction
}) => (
<IconButton onClick={onClickAction} touch>
<ContentAdd />
</IconButton>
)
const ClientIcons = ({
menuActions
}) => (
<div>
<IconButton onClick={menuActions.reverseFavouriteMenu}>
<ActionFavorite/>
</IconButton>
<IconButton onClick={menuActions.reverseCartMenu}>
<ActionShoppingCart/>
</IconButton>
</div>
)
const RightIcons = ({
isAdmin,
menuActions
}) => ( isAdmin ?
<CreateIcon onClickAction={menuActions.reverseCreateMenu}/>
:
<ClientIcons menuActions={menuActions}/>
)
const Header = ({
isAdmin = false,
menuActions
}) => (
<Toolbar style={style.bar}>
<ToolbarGroup float="left" firstChild>
<MenuIcon onClickAction={menuActions.reverseLeftMenu}/>
</ToolbarGroup>
<ToolbarTitle text="TUDELARTE"/>
<ToolbarGroup float="right" lastChild>
<RightIcons menuActions={menuActions} isAdmin={isAdmin}/>
</ToolbarGroup>
</Toolbar>
)
Header.propTypes = {
isAdmin: React.PropTypes.bool,
menuActions: React.PropTypes.object,
}
function mapStateToProps(state, ownProps) {
// You should not return the full state, but only the parts of it you need
return state;
}
function mapDispatchToProps(dispatch) {
return {
menuActions: bindActionCreators(MenuActionCreators, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Header);https://stackoverflow.com/questions/35300088
复制相似问题