Undefined 不是 this.state 对象上的对象



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

Unhandeld JS Exception: 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);

最新更新