navigation.dispatch 在 reactnavigation 中未定义

navigation.dispatch is undefined in reactnavigation

我正在使用 reactnavigation 和 redux 创建一个 react-native 应用程序。

加载应用程序时,我从 NavContainer 收到以下警告:Warning: Failed prop type: The prop 'navigation.dispatch' is marked as required in 'CardStack', but its value is 'undefined'

当我尝试通过 this.props.navigation.navigate('Station'); 导航页面时,这会导致错误,因为 navigation.dispatch 不是函数

该应用程序有一个 NavContainer,我猜它缺少一些东西,因为 dispatch 在渲染函数中未定义:

import React, { Component } from 'react'
import { addNavigationHelpers } from 'react-navigation'
import AppNavigator from '../lib/navigationConfiguration'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux';
import { ActionCreators } from '../actions';

class NavContainer extends Component {

  render(){
    const { dispatch, navigationState} = this.props
    return (
      <AppNavigator
        navigation={
          addNavigationHelpers({
            dispatch: dispatch,
            state: navigationState
          })
        }
      />
    )
  }
}
function mapStateToProps(state){
  return {
    navigationState: state.nav
  }
}
function mapDispatchToProps(dispatch){
  return bindActionCreators(ActionCreators, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(NavContainer)

当您定义 mapDispatchToProps 时,connect 不会将 dispatch 传递给包装组件。这就是 this.props.dispatch 未定义的原因。要解决这个问题,您可以这样做:

function mapDispatchToProps(dispatch){
  return Object.assign({dispatch: dispatch}, bindActionCreators(ActionCreators, dispatch));
}