reactjs - React hooks 单选按钮列表给出警告:列表中的每个孩子都应该有一个唯一的“key”道具
问题描述
尽管带有单选按钮的表单按预期工作(检查所选选项并显示对应的组件),但我不断收到唯一键道具警告。
我正在使用对象数组将数据提供给渲染函数并返回无线电输入 jsx。
代码如下:(主要形式)
import React, {useState} from 'react'
import FormOperationOptions from './FormOptions'
import UserConfig from './user-config/UserConfig'
const Form = () => {
const[operation, setOperation] = useState('')
const selectOperationOnChange = (event) =>{
setOperation(event.target.value);
}
const operationsListKey = FormOperationOptions.map((operations)=>{
return operations.id})
const renderAllOperations = (value, key) => {
return(
<div>
<input type='radio'
key={key}
value={value}
checked={value===operation? true:false}
readOnly
/>
<label htmlFor={value}>{value}</label><br/>
</div>
)
}
const selectedOperation = () => {
if(operation === 'userConfig'){return(<div><UserConfig /></div>)}
}
return(
<div>
<h3>Choose operation type:</h3>
<form
onChange={selectOperationOnChange}
>
{FormOperationOptions.map((operations)=>{
return renderAllOperations(operations.selectedOption, operationsListKey);})}
</form>
{selectedOperation()}
</div>
)
}
export default Form
(表格的数据来自哪里)
const FormOptions = [
{
id:1,
selectedOption: 'userConfig',
},
{
id:2,
selectedOption: 'gitIgnore',
},
{
id:3,
selectedOption: 'localRepository',
},
{
id:4,
selectedOption: 'remoteRepository',
},
]
export default FormOptions
和 UserConfig 组件:
import React from 'react'
const UserConfig = () =>{
return(
<div> UserConfig component </div>
)
}
export default UserConfig
感谢您的时间和投入:)
解决方案
您在错误的元素中添加了“键”。它应该添加在“div”而不是“input”上。
const renderAllOperations = (value, key) => {
return(
<div key={key}>
<input type='radio'
value={value}
checked={value===operation? true:false}
readOnly
/>
<label htmlFor={value}>{value}</label><br/>
</div>
)
}
如果“输入”需要密钥,您可以传递另一个,如下所示
const renderAllOperations = (value, key) => {
return(
<div key={key}>
<input type='radio'
key={`radio_${key}`}
value={value}
checked={value===operation? true:false}
readOnly
/>
<label htmlFor={value}>{value}</label><br/>
</div>
)
}
推荐阅读
- java - 如何在多个类中使用@RabbitListener?
- sql - 如何仅使用先前加载的行数来选择行?
- autodesk-forge - 如何从 Bim360 加载 otg?
- c++ - QT:将其签名中具有基本类型的信号连接到其签名中具有 QVariant 的插槽
- java - 如果 Table1 和 Table2 表中有一些相同的行名,那么如何在 java 中读取它们?
- javascript - 如何促进不同Web应用程序之间的通信?
- java - 模式没有给出正确的结果
- php - react-native : GET 或 Head 请求不允许正文
- r - 如何在从蜡笔捕获 ANSI 颜色代码时获得 capture.output 功能?
- java - 连接到 HTTPS 站点时出现 SSLHandshakeException