19

在我的mapStateToProps函数中,我设置idTokenaccessToken存储在状态中的值。这很有效,因为我已经能够从组件中引用这些值。在mapDispatchToProps我尝试使用这些道具作为我的行动中的论据。但是,ownProps是一个空对象。为什么没有idTokenand 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

为什么我无法访问idTokenand accessTokenfrom ownProps?如果这是不正确的模式,应该如何idToken访问accessToken

谢谢!

4

1 回答 1

33

mapStateToPropsandmapDispatchToProps中,ownProps参数是指组件通过属性接收到的 props,例如:

<AddQuestionButton isVisible={ true } />

isVisible属性将作为ownProps. 这样,你就可以有一个组件从 redux 接收一些 props,从属性接收一些 props。

connect方法本身有第三个参数,称为mergeProps

[mergeProps(stateProps, dispatchProps, ownProps): props] (Function): 如果指定,则传递 mapStateToProps()、mapDispatchToProps() 和父 props 的结果。您从中返回的普通对象将作为道具传递给包装的组件。您可以指定此函数以根据 props 选择状态切片,或将动作创建者绑定到 props 中的特定变量。如果省略它,则默认使用 Object.assign({}, ownProps, stateProps, dispatchProps)。

在合并道具中,您实际上可以将所有道具组合在一起,正如您在 Dan Abramov 对这个问题的回答中看到的那样:

function mapStateToProps(state, ownProps) {
  return {
    isFollowing: state.postsFollowing[ownProps.id]
  };
}

function mergeProps(stateProps, dispatchProps, ownProps) {
  const { isFollowing } = stateProps;
  const { dispatch } = dispatchProps;
  const { id } = ownProps;

  const toggle = isFollowing ?
    unfollowPostActionCreator :
    followPostActionCreator;

  return {
    ...stateProps,
    ...ownProps,
    toggleFollow: () => dispatch(toggle(id)))
  };
}

ToggleFollowButton = connect({
  mapStateToProps,
  null, // passing null instead of mapDispatchToProps will return an object with the dispatch method
  mergeProps
})(ToggleFollowButton)
于 2016-04-10T04:57:39.733 回答