【问题标题】:How can I resolve this warning ? "Encountered Two Children with the same key, `.$1/.$2`"如何解决此警告? “遇到两个孩子用同一个钥匙,`.$1/.$2`”
【发布时间】:2022-01-10 07:21:30
【问题描述】:

我正在使用 import "react-native-form-select-picker" 在我的 react native 应用程序中进行选择输入,并且代码工作正常,但它仍然给我一个警告,因为 "Encountered Two Children with the same key , `.$1/.$2".那么我该如何解决这个问题有人可以帮忙吗?以下是我的代码行:

import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, } from 'react-native';
import SelectPicker from 'react-native-form-select-picker';

const options = ["Aadhar Card", "Bank Passbook", "Driving Licence", "Pan Card"];

// create a component
const UpdateDocument = ({ navigation }) => {

    const [selected, setSelected] = useState();

    return (
        <View style={styles.container}>
            <View style={styles.docBox}>
                <SelectPicker
                    placeholder="Select document to Update"
                    style={styles.selectBox}
                    onValueChange={(value) => {
                        // Do anything you want with the value. 
                        // For example, save in state.
                        setSelected(value);
                    }}
                    selected={selected}
                >

                    {Object.values(options).map((val, index) => (
                        <SelectPicker.Item label={val} value={val} key={} />
                    ))}

                </SelectPicker>
            </View>
        </View>
    );
};

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    docBox: {
        paddingVertical: 10,
        paddingHorizontal: 10,
        borderBottomColor: '#aaa',
        borderBottomWidth: 1,
    },
    selectBox: { borderColor: '#555', borderWidth: 1, borderRadius: 4, }
});

//make this component available to the app
export default UpdateDocument;

【问题讨论】:

  • 正如错误所说。 key={} key 不会因不同的孩子而改变 - 你不能这样做,你需要为每个孩子选择一个唯一的键。

标签: javascript arrays react-native unique-key


【解决方案1】:

键帮助 React 识别哪些项目已更改、添加或删除。这就是为什么 React 希望您在迭代对象列表以呈现多个 JSX 元素时为每个元素添加唯一键。 如果省略键,列表中的项目将无法获得稳定的身份,React 会在控制台中对您大喊:警告:列表中的每个孩子都应该有一个唯一的“键”道具。 p>

因此,如果您在选项 lst 中的每个选项都是唯一的,那么您就可以这样做。

{Object.values(options).map((val, index) => (
                        <SelectPicker.Item label={val} value={val} key={val} />
                    ))}

【讨论】:

  • 谢谢你的帮助。它解决了我的问题
猜你喜欢
  • 2018-10-06
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
相关资源
最近更新 更多