在我的mapStateToProps函数中,我将idToken和accessToken设置为存储在状态的值.这样做可以从组件中引用这些值.在mapDispatchToProps中,我尝试在我的操作中使用这些道具作为参数.但是,ownProps是一个空对象.为什么没有idToken和accessToken?
容器:
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?
谢谢!
在mapStateToProps和mapDispatchToProps中,ownProps参数是指组件通过属性接收的道具,例如:
< 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)