React Native Navigator: ожидался класс компонента, получил [объект Object]

ошибка, указанная в заголовке, отображается, когда я пытаюсь загрузить новый Component через компонент Navigator.

Мое представление с компонентом "Навигатор" выглядит следующим образом:

render(){
    return(
      <Navigator
        initialRoute={{name: 'Feed', component: Feed}}
        renderScene={(route, navigator) => {
            if(route.component){
              return React.createElement(route.component, {navigator, ...this.props})
            }
          }
        }
      />
    )
  }
}

InitialRoute отлично отображает правильный View. Отрисовываемый дочерний компонент Feed содержит список кнопок, которые обновляют навигатор и заставляют его отображать новый компонент следующим образом:

  updateRoute(route){
    this.props.globalNavigator(route)
    this.props.navigator.push({
      name: route.displayLabel,
      component: route.label
    })
  }

  render(){
    return(
      <View style={styles.bottomNavSection}>
        {
          this.state.navItems.map((n, idx) => {
            return(
              <TouchableHighlight
                key={idx}
                style={this.itemStyle(n.label, 'button')}
                onPress={this.updateRoute.bind(this, n)}
              >
                <Text
                  style={this.itemStyle(n.label, 'text')}
                >
                  {n.displayLabel}
                </Text>
              </TouchableHighlight>
            )
          })
        }
      </View>
    )
  }

Обратите внимание, что function updateRoute(route) получает имя нового компонента следующим образом: onPress={this.updateRoute.bind(this, n)}. Например, где n равно {displayLabel: 'Start', label: 'Feed', icon: ''},.

Редактировать содержимое моего компонента Profil.js:

import React, { Component } from 'react'
import ReactNative from 'react-native'
import API from '../lib/api'

import BottomNavigation from '../components/BottomNavigation'

const {
  ScrollView,
  View,
  Text,
  TouchableHighlight,
  StyleSheet,
} = ReactNative

import { connect } from 'react-redux'

class Profil extends Component {

  constructor(props){
    super(props)
  }

  render(){
    return(
      <View style={styles.scene}>
        <ScrollView style={styles.scrollSection}>
          <Text>Profil</Text>
        </ScrollView>
        <BottomNavigation {...this.props} />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  scene: {
    backgroundColor: '#0f0f0f',
    flex: 1,
    paddingTop: 20
  },
  scrollSection: {
    flex: .8
  }
})

function mapStateToProps(state){
  return {
    globalRoute: state.setGlobalNavigator.route
  }
}

export default connect(mapStateToProps)(Profil)

person noa-dev    schedule 27.12.2016    source источник


Ответы (2)


Проблема заключалась в том, что onPress={this.updateRoute.bind(this, n)} не содержал правильной ссылки на компонент, а вместо этого содержал имя компонента как String.

Исправлено изменением функции:

 updateRoute(route){
    this.props.globalNavigator(route)
    this.props.navigator.push({
      name: route.displayLabel,
      component: route.component
    })
  }

и улучшение состояния с помощью ссылки на компонент и импорт компонента в начало документа.

this.state = { 
   navItems: [
      {displayLabel: 'Start', label: 'Feed', icon: start, component: Feed},
   ]
}
person noa-dev    schedule 27.12.2016

Я думаю, вы забыли экспортировать свой компонент.

person Santosh Sharma    schedule 27.12.2016
comment
Какой компонент? Профиль? В Profil внизу есть экспортная ведомость. - person noa-dev; 27.12.2016