简体   繁体   English

未定义不是this.state对象上的对象

[英]Undefined is not an object on this.state object

I am setting up a React Native App. 我正在设置一个React Native App。 In this App i am trying to include a reusable Top Navigation Component, which accepts an array of strings and then renders them appropriately. 在这个应用程序中,我试图包括一个可重用的顶部导航组件,该组件接受字符串数组,然后适当地呈现它们。 When i am trying to compare the array string to a given string, it throws the following error: 当我尝试将数组字符串与给定字符串进行比较时,它将引发以下错误:

Unhandeld JS Exception: TypeError: undefined is not an object (evaluating 'this.state.choseTopNavigation' Unhandeld JS异常:TypeError:undefined不是对象(正在评估'this.state.choseTopNavigation'

Inserting a string to compare works just fine 插入字符串进行比较就可以了

Setting up state object in constructor 在构造函数中设置状态对象

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ScrollView, FlatList} from 'react-native';
import {Header, TopNavigationButton}  from './components';

type Props = {};
export default class App extends Component<Props> {


constructor(props) {
  super(props);
  this.state = { 
    topNavigationOptions : [
      {key: 'Quick Search'},
      {key: 'Person Search'}],
      chosenTopNavigation: 
      "Quick Search",
  };

}

}



renderItem({item}){
  if (item.key == this.state.chosenTopNavigation) {
    return (
        <TopNavigationButton>
          {item.key}
        </TopNavigationButton>
      )
  } else {
    return (
      <Text style = {styles.unchosenTextStyle}>
        {item.key}
      </Text>
    )
  }
}


  render() {
    return (
      <View>

        <Header>Header</Header>
        <ScrollView horizontal = {true}>
          <View style = {styles.navigationContainer}>
            <TopNavigationButton>Quick Search</TopNavigationButton>
            <Text style = {styles.unchosenTextStyle}>Person Search</Text>
          </View>
        </ScrollView>

      <FlatList 
        horizontal
        data={this.state.topNavigationOptions}
        renderItem = {this.renderItem}
      />

      </View>  
    );
  }
}

Note This Works 注意此工程

renderItem({item} ){
  if (item.key == "Quick Search") { //inserting a string directly works
    return (
        <TopNavigationButton>
          {item.key}
        </TopNavigationButton>
      )
  } else {
    return (
      <Text style = {styles.unchosenTextStyle}>
        {item.key}
      </Text>
    )
  }
}

Thanks a lot for your help! 非常感谢你的帮助!

Either you can make your function as arrow function like this: 您可以使您的功能成为箭头函数,如下所示:

renderItem = ({item}) => {
// your existing code
}

or you need to bind your function in constructor like this: 或者您需要像这样在构造函数中绑定函数:

this.renderItem = this.renderItem.bind(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM