首页 文章

React-Redux mapDispatchToProps没有接收到mapStateToProps

提问于
浏览
15

在我的 mapStateToProps 函数中,我将 idTokenaccessToken 设置为存储在state中的值 . 这是有效的,因为我已经能够从组件中引用这些值 . 在 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

零件:

'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 访问 idTokenaccessToken ?如果这种方式不正确,应该如何访问 idTokenaccessToken

谢谢!

1 回答

  • 28

    mapStateToPropsmapDispatchToProps 中, 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 Abramov的回答中所看到的那样issue

    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)
    

相关问题