我得到了一个错误:

不变冲突:withNavigation只能在视图上使用

我不知道为什么,因为我在我的应用程序的其他组件中使用了withNavigation,而且很有效.我看不出它工作的组件与导致错误的组件有什么区别.

代码:

组成部分:

const mapStateToProps = (state: State): Object => ({
  alertModal: state.formControls.alertModal
})

const mapDispatchToProps = (dispatch: Dispatch<*>): Object => {
  return bindActionCreators(
    {
      updateAlertModalHeight: updateAlertModalHeight,
      updateAlertModalIsOpen: updateAlertModalIsOpen,
      updateHasYesNo: updateAlertModalHasYesNo
    },
    dispatch
  )
}

class AlertModalView extends Component<AlertModalProps, State> {
  render(): Node {
    return (
      <View style={alertModalStyle.container}>
        <PresentationalModal
          style={presentationalModalStyle}
          isOpen={this.props.alertModal.isOpen}
          title={this.props.alertModal.title}
          navigation={this.props.navigation}
          updateHasYesNo={this.props.updateHasYesNo}
          message={this.props.alertModal.message}
          updateAlertModalHeight={this.props.updateAlertModalHeight}
          viewHeight={this.props.alertModal.viewHeight}
          hasYesNo={this.props.alertModal.hasYesNo}
          yesClicked={this.props.alertModal.yesClicked}
          updateAlertModalIsOpen={this.props.updateAlertModalIsOpen}
        />
      </View>
    )
  }
}

// $FlowFixMe
const AlertModalViewComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(AlertModalView)

export default withNavigation(AlertModalViewComponent)

stackNavigator:

import React from 'react'
import { View, SafeAreaView } from 'react-native'
import Icon from 'react-native-vector-icons/EvilIcons'
import Add from '../product/add/view'
import Login from '../user/login/view'
import Search from '../product/search/query/view'
import { Image } from 'react-native'
import { StackNavigator, DrawerNavigator, DrawerItems } from 'react-navigation'

const AddMenuIcon = ({ navigate }) => (
  <View>
    <Icon
      name="plus"
      size={30}
      color="#FFF"
      onPress={() => navigate('DrawerOpen')}
    />
  </View>
)

const SearchMenuIcon = ({ navigate }) => (
  <Icon
    name="search"
    size={30}
    color="#FFF"
    onPress={() => navigate('DrawerOpen')}
  />
)

const Stack = {
  Login: {
    screen: Login
  },
  Search: {
    screen: Search
  },
  Add: {
    screen: Add
  }
}


const DrawerRoutes = {
  Login: {
    name: 'Login',
    screen: Login
  },
  'Search Vegan': {
    name: 'Search',
    screen: StackNavigator(Stack.Search, {
      headerMode: 'none'
    }),
    navigationOptions: ({ navigation }) => ({
      drawerIcon: SearchMenuIcon(navigation)
    })
  },
  'Add vegan': {
    name: 'Add',
    screen: StackNavigator(Stack.Add, {
      headerMode: 'none'
    }),
    navigationOptions: ({ navigation }) => ({
      drawerIcon: AddMenuIcon(navigation)
    })
  }
}

const CustomDrawerContentComponent = props => (
  <SafeAreaView style={{ flex: 1, backgroundColor: '#3f3f3f', color: 'white' }}>
    <View>
      <Image
        style={{
          marginLeft: 20,
          marginBottom: 0,
          marginTop: 0,
          width: 100,
          height: 100,
          resizeMode: 'contain'
        }}
        square
        source={require('../../images/logo_v_white.png')}
      />
    </View>
    <DrawerItems {...props} />
  </SafeAreaView>
)

const Menu = StackNavigator(
    {
      Drawer: {
        name: 'Drawer',
        screen: DrawerNavigator(DrawerRoutes, {
          initialRouteName: 'Login',
          drawerPosition: 'left',
          contentComponent: CustomDrawerContentComponent,
          contentOptions: {
            activeTintColor: '#27a562',
            inactiveTintColor: 'white',
            activeBackgroundColor: '#3a3a3a'
          }
        })
      }
    },
    {
      headerMode: 'none',
      initialRouteName: 'Drawer'
    }
  )


export default Menu

在这里,我呈现了我的应用程序组件中的StackNavigatorMenu:

import React, { Component } from 'react'
import Menu from './menu/view'
import Props from 'prop-types'
import { Container } from 'native-base'
import { updateAlertModalIsOpen } from './formControls/alertModal/action'
import AlertModalComponent from './formControls/alertModal/view'
import UserLoginModal from './user/login/loginModal/view'

class Vepo extends Component {
  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() => {})
    store.dispatch(this.props.fetchUserGeoCoords())
    store.dispatch(this.props.fetchSearchQueryPageCategories())
    store.dispatch(this.props.fetchCategories())
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render(): Object {
    return (
      <Container>
        <Menu store={this.context} />
        <AlertModalComponent
          yesClicked={() => {
            updateAlertModalIsOpen(false)
          }}
        />

        <UserLoginModal />
      </Container>
    )
  }
}
Vepo.contextTypes = {
  store: Props.object
}

export default Vepo

我的根组件:

export const store = createStore(
  rootReducer,
  vepo,
  composeWithDevTools(applyMiddleware(createEpicMiddleware(rootEpic)))
)

import NavigationService from './navigationService'

export const App = () => (
  <Provider store={store}>
      <Vepo
        fetchUserGeoCoords={fetchUserGeoCoords}
        fetchSearchQueryPageCategories={fetchSearchQueryPageCategories}
        fetchCategories={fetchCategories}
      />
  </Provider>
)
AppRegistry.registerComponent('vepo', () => App)

我已将我的Vepo组件更改为此,以实现vahissan的答案:

import React, { Component } from 'react'
import Menu from './menu/view'
import Props from 'prop-types'
import { Container } from 'native-base'
import { updateAlertModalIsOpen } from './formControls/alertModal/action'
import AlertModalComponent from './formControls/alertModal/view'
import UserLoginModal from './user/login/loginModal/view'

import NavigationService from './navigationService'

class Vepo extends Component {
  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() => {})
    store.dispatch(this.props.fetchUserGeoCoords())
    store.dispatch(this.props.fetchSearchQueryPageCategories())
    store.dispatch(this.props.fetchCategories())
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render(): Object {
    return (
      <Container>
        <Menu
          store={this.context}
          ref={navigatorRef => {
            NavigationService.setTopLevelNavigator(navigatorRef)
          }}>
          <AlertModalComponent
            yesClicked={() => {
              updateAlertModalIsOpen(false)
            }}
          />
        </Menu>
        <UserLoginModal />
      </Container>
    )
  }
}
Vepo.contextTypes = {
  store: Props.object
}

export default Vepo

没有错误,但不再显示alertModal

推荐答案

在react navigation中,主StackNavigator创建一个上下文提供程序,如果组件树中低于其级别的组件使用上下文使用者,则navigationprops 将可用于该组件.

使用上下文消费者访问navigationprops 的两种方法是将组件添加到StackNavigator,或使用withNavigation函数.然而,由于React的上下文API的工作方式,任何使用withNavigation函数的组件都必须位于组件树中StackNavigator的下方.

如果您仍然希望访问navigationprops ,而不管它在组件树中的位置如何,则必须将StackNavigator的引用存储在一个模块中.下面的react navigation指南将帮助您做到这一点

React-native相关问答推荐

'无法解析模块.安装react-native-pager-view后的实用程序/平台

React Native:任务 ':app:checkDebugDuplicateClasses' 执行失败

如何在 React / React Native 中使用 Emscripten 编译的 JavaScript

ReactNative:在所有组件和操作之间共享 sqlite 实例的最佳方法

TypeError:undefined is not an object(判断'navigator.geolocation.requestAuthorization')

在 react-native 中调试原生 java 代码

如何在 React-Native Android 中检测拖动事件的结束

使用 Android NDK 在 C 或 C++ 中创建 react-native Native Module?

Xcode 12 问题:Build input file cannot be found

React-Native 构建失败的应用程序:mergeDebugAssets

在 UIManager 中找不到RNCSafeAreaView

TouchableHighlight onPress 不起作用

如何在 React Native 中将静态图像拉伸为背景?

为什么 Android Studio 强制使用 Android 支持库中的 Androidx?

如何将 Leaflet.js 与 react-native 一起使用

Ipad 上的 React Native - 错误 - could not connect to development server

带有父 PanResponder 的 TouchableOpacity

Tools > Android 菜单在 Android Studio 中不存在

错误 React Native CLI 对本机依赖项使用自动链接,但以下模块是手动链接的

如何允许 react-native 启用对 JSX(扩展)文件的支持