[英]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.