【问题标题】:Unable to use the item value from FlatLists renderItem in react native无法在本机反应中使用来自 FlatLists renderItem 的项目值
【发布时间】:2020-04-15 20:19:57
【问题描述】:

我对编码很陌生,所以真的很挣扎,但我相信这很简单。

当使用FlatlistrenderItemitem

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

&lt;Text&gt;{item}&lt;/Text&gt; 工作正常,首先渲染 9,然后渲染 10。

但是&lt;Text&gt;{GLOBAL.products[item].title}&lt;/Text&gt; 给了我错误:

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

&lt;Text&gt;{GLOBAL.products[**{**item**}**].title}&lt;/Text&gt; 不起作用。还有_renderItem = ( **{**item**}** ) =&gt; {

&lt;Text&gt;{GLOBAL.products[9].title}&lt;/Text&gt; 工作正常。也试过GLOBAL.products[parseInt(item)].title

【问题讨论】:

    标签: javascript reactjs react-native react-native-flatlist


    【解决方案1】:

    很明显你不知道 JavaScript 对象和子调用。当你调用一个孩子但它的父母不存在时,你肯定也会在 React Native 的 Text 组件中遇到错误,你应该至少传递一个空字符串。

    你应该防御性地培养孩子的连锁呼唤。为此,我建议您阅读 optional chaining 并使用 this link 将其添加到您的项目中。

    安装后你可以编写_renderItem函数如下:

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

    我更喜欢第二个。这种防御性编程可防止您的应用崩溃。

    【讨论】:

    • 我不认为这符合我的要求,它为&lt;Text&gt;{item}&lt;/Text&gt; 呈现正确的值,但总是为&lt;Text&gt;{get(GLOBAL, ['products', 'item', 'title'], '')}&lt;/Text&gt; 返回一个空字符串,这是为什么呢?我可以在第一个文本元素中使用 item 的值,但不能在第二个文本元素中使用。这阻止了我得到一个错误,但只是因为它再次使用默认的'',这工作正常&lt;Text&gt;{get(GLOBAL, ['products', '9', 'title'], '')}&lt;/Text&gt;,当&lt;Text&gt;{item}&lt;/Text&gt;打印一个9时,&lt;Text&gt;{get(GLOBAL, ['products', 'item', 'title'], '')}&lt;/Text&gt;仍然不起作用
    • 亲爱的@skylisk,您的问题是关于错误,您的应用程序因嵌套对象链接错误而崩溃,该错误具有undefined 父级。因此,通过使用 lodash get 函数,您的错误消失并且您的应用程序不会崩溃。所以这就是这个问题的答案。现在,你还有一个问题。 _为什么get(GLOBAL, ['products', '9', 'title'], '') 返回值而get(GLOBAL, ['products', 'item', 'title'], '') 没有。您可以解决这个问题并询问另一个具有具体细节的问题。希望能帮到你。
    • 抱歉,第一次发帖,所以可能不清楚。会的!
    • 不,伙计,@skylisk,没有必要道歉,这是你的问题。一遍又一遍地问,直到找到你的答案。
    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多