簡體   English   中英

無法在本機反應中使用來自 FlatLists renderItem 的項目值

[英]Unable to use the item value from FlatLists renderItem in react native

我對編碼很陌生,所以真的很掙扎,但我相信這很簡單。

使用Flatlist renderItem item

_renderItem = ( item ) => {
    return (<View style={{ flex: 1 }}>
        <Text>{item}</Text>
        <Text>{GLOBAL.products[item].title}</Text>
    </View >)
};

render() {
    return (
        <View style={styles.list}>
            <FlatList
                data={[9,10]}
                renderItem={ this._renderItem} />
        </View>
    )
}

<Text>{item}</Text>工作正常,首先渲染 9,然后渲染 10。

但是<Text>{GLOBAL.products[item].title}</Text>給了我錯誤:

TypeError: TypeError: undefined is not an object(評估 '_global.default.products[item].title

<Text>{GLOBAL.products[**{**item**}**].title}</Text>不起作用。 還有_renderItem = ( **{**item**}** ) => {

<Text>{GLOBAL.products[9].title}</Text>工作正常。 也嘗試過GLOBAL.products[parseInt(item)].title

很明顯你不知道 JavaScript Object 和兒童電話。 當你調用一個孩子但它的父母不存在時,你肯定也會在 React Native 的Text組件中遇到錯誤,你應該至少傳遞一個空字符串。

你應該防御性地培養孩子的連鎖呼喚。 為此,我建議您閱讀有關可選鏈接的信息,並使用此鏈接將其添加到您的項目中。

安裝后,您可以編寫_renderItem function 如下所示:

_renderItem = item => (
  <View style={{ flex: 1 }}>
    <Text>{item}</Text>
    <Text>{GLOBAL?.products[item]?.title || ''}</Text>
  </View >
);

或者有一個更好的方法來使用lodash.get通過安裝它yarn add lodash.getnpm install --save lodash.get ,然后像下面這樣使用它:

import get from 'lodash.get';

~~~

_renderItem = item => (
  <View style={{ flex: 1 }}>
    <Text>{item}</Text>
    <Text>{get(GLOBAL, ['products', 'item', 'title'], '')}</Text>
  </View >
);

我更喜歡第二個。 這種防御性編程可防止您的應用程序崩潰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM