容器:
import { connect } from 'react-redux' import { toggleAddQuestionModal,fetchFriends } from '../actions' import AddQuestionButtonComponent from '../components/AddQuestionButton' const mapStatetoProps = (state) => { auth = state.auth return { idToken: auth.token.idToken,accesstoken: auth.profile.identities[0].accesstoken,} } const mapdispatchToProps = (dispatch,ownProps) => { return { didPress: (idToken,accesstoken) => { dispatch(toggleAddQuestionModal(true)) dispatch(fetchFriends(ownProps.idToken,ownProps.accesstoken)) } } } AddQuestionButton = connect( mapStatetoProps,mapdispatchToProps )(AddQuestionButtonComponent) export default AddQuestionButton
零件:
'use strict'; import React,{ Text,View,TouchableHighlight,PropTypes,} from 'react-native' import styles from './styles' const AddQuestionButton = ({ didPress,idToken,accesstoken }) => ( <TouchableHighlight style={styles.actionButton} onPress={didPress(idToken,accesstoken)}> <Text style={styles.actionButtonText}>+</Text> </TouchableHighlight> ) AddQuestionButton.propTypes = { idToken: PropTypes.string.isrequired,accesstoken: PropTypes.string.isrequired,didPress: PropTypes.func.isrequired,} export default AddQuestionButton
为什么我不能从ownProps访问idToken和accesstoken?如果这样做不正确,应该如何访问idToken和accesstoken?
谢谢!
< AddQuestionButton isVisible = {true} />
isVisible属性将作为ownProps传递.这样,您可以拥有一个从redux接收一些道具的组件,以及一些属性的道具.
connect
方法本身有一个名为mergeProps的第三个参数:
[mergeProps(stateProps,dispatchProps,ownProps): props] (Function):
If specified,it is passed the result of mapStatetoProps(),
mapdispatchToProps(),and the parent props. The plain object you
return from it will be passed as props to the wrapped component. You
may specify this function to select a slice of the state based on
props,or to bind action creators to a particular variable from props.
If you omit it,Object.assign({},ownProps,stateProps,dispatchProps)
is used by default.
在合并道具中,您实际上将所有道具结合在一起,正如丹·阿布拉莫夫在这个issue年的答案中所看到的那样:
function mapStatetoProps(state,ownProps) { return { isFollowing: state.postsFollowing[ownProps.id] }; } function mergeProps(stateProps,ownProps) { const { isFollowing } = stateProps; const { dispatch } = dispatchProps; const { id } = ownProps; const toggle = isFollowing ? unfollowPostActionCreator : followPostActionCreator; return { ...ownProps,toggleFollow: () => dispatch(toggle(id))) }; } ToggleFollowButton = connect({ mapStatetoProps,null,// passing null instead of mapdispatchToProps will return an object with the dispatch method mergeProps })(ToggleFollowButton)
原文地址:https://www.jb51.cc/react/300742.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。