【问题标题】:Two children with the same key in React Native with Native Base使用 Native Base 的 React Native 中具有相同键的两个孩子
【发布时间】:2019-11-05 08:59:15
【问题描述】:

如何解决以下错误:警告:遇到两个孩子使用相同的密钥 [object Object]。密钥应该是唯一的,以便组件在更新时保持其身份。非唯一键可能会导致子项被重复和/或省略——这种行为不受支持,并且可能在未来的版本中发生变化。

这是我的清单:

<List style={custom.PartList}>
     <FlatList extraData={this.state} data={this.state.data} keyExtractor={this._keyExtractor.bind(this)} renderItem={this._renderItem.bind(this)} />
</List>

这是我的列表项:

   /* Render Item - Render One Row - Item - (Tool) */
    _renderItem({ item }) {
        const custom = styles(this.props);

        return (
            <View style={custom.PartView}>
                <ListItem style={custom.PartListItem} onPress={() => this._handleRead(item.tool_id, item.tool_name, item.tool_description, item.tool_count, item.tool_availability)}>
                    <Image style={custom.PartImage} source={require('@app/assets/images/tools.png')}/>
                    <Text style={custom.PartName}>{item.tool_name}</Text>
                </ListItem>
            </View>
        );
    }
    /* /Render Item - Render One Row - Item - (Tool)/ */

这就是我的 keyExtractor 方法:

/* Key Extractor Method - For Index Tools */
  _keyExtractor(index) {
      return index.toString();
  }
/* /Key Extractor Method - For Index Tools/ */

【问题讨论】:

    标签: javascript list react-native listitem native-base


    【解决方案1】:

    对于平面列表代码

    <List style={custom.PartList}>
         <FlatList extraData={this.state} data={this.state.data}
        keyExtractor={(item, index) => index.toString()}
     renderItem={this._renderItem.bind(this)} />
    </List>
    

    【讨论】:

    • 这是可行的,但是当我有主页的子页面时,我再次遇到相同的错误。奇怪的是我在子页面中没有列表。这是什么?
    • 你能解释更多吗?
    • 但现在我得到另一个错误:警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 componentWillUnmount 方法中取消所有订阅和异步任务。
    • 你的代码中有监听器吗?你实现了 componentWillUnmount() 吗?
    • 是的。我已经实现了 componentDidMount、componentDidUpdate 和 componentWillUnmount。
    【解决方案2】:

    您将this 绑定到keyExtractor 函数,因此它将提供this 对象作为第一个参数(您将其称为index)。因此返回值将始终是 Object (= [Object object]) 的字符串表示形式

    简单的解决方案就是声明keyExtractor={this.keyExtractor},不进行任何绑定。

    【讨论】:

    • 如果我声明我再次遇到同样的错误。这是未定义的。
    【解决方案3】:

    对我来说,它的添加方式完全像这样:

    <FlatList
        data={mySkills}
        keyExtractor={this.keyExtractor}
        renderItem={({item, index}) => <SkillCard key={index} skill={item} />}
      />
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 1970-01-01
      • 2019-02-12
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多