React-Redux mapDispatchToProps没有接收到mapStateToProps

Col*_*ole 19 redux react-redux

在我的mapStateToProps函数中,我设置idTokenaccessToken存储在状态中的值.这是有效的,因为我已经能够从组件中引用这些值.在mapDispatchToProps我尝试使用这些道具作为我的行动中的参数.但是,ownProps是一个空对象.为什么它不具备idTokenaccessToken

容器:

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
Run Code Online (Sandbox Code Playgroud)

零件:

'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
Run Code Online (Sandbox Code Playgroud)

为什么我无法访问idTokenaccessTokenownProps?如果这个不正确的模式,应该如何idTokenaccessToken访问?

谢谢!

Ori*_*ori 33

mapStateToProps和中mapDispatchToProps,ownProps参数引用组件通过属性接收的props,例如:

<AddQuestionButton isVisible={ true } />

isVisible属性将作为传递ownProps.通过这种方式,您可以拥有一个从redux接收一些道具的组件,以及一些来自属性的道具.

connect方法本身有一个名为的第三个参数mergeProps:

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

在合并的道具,你真正得到的所有道具相结合,你可以在此答案由Dan阿布拉莫夫这个看问题:

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)
Run Code Online (Sandbox Code Playgroud)