繁体   English   中英

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

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

我正在设置一个React Native App。 在这个应用程序中,我试图包括一个可重用的顶部导航组件,该组件接受字符串数组,然后适当地呈现它们。 当我尝试将数组字符串与给定字符串进行比较时,它将引发以下错误:

Unhandeld JS异常:TypeError:undefined不是对象(正在评估'this.state.choseTopNavigation'

插入字符串进行比较就可以了

在构造函数中设置状态对象

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>  
    );
  }
}

注意此工程

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>
    )
  }
}

非常感谢你的帮助!

您可以使您的功能成为箭头函数,如下所示:

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

或者您需要像这样在构造函数中绑定函数:

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

暂无
暂无

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

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