React hooks 单选按钮列表给出警告:列表中的每个孩子都应该有一个唯一的"key"道具



尽管带有单选按钮的表单按预期工作(选中所选选项并显示相应组件(,但我一直收到唯一的密钥道具警告
我使用一个对象数组将数据提供给render函数并返回无线电输入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

感谢您的时间和投入:(

您在错误的元素中添加了"key"。它应该被添加到";div";而不是";输入";。

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

你能试试这个吗:

return(
<div>
<h3>Choose operation type:</h3>
<form 
onChange={selectOperationOnChange}
>
{FormOperationOptions.map((operations)=>{
return renderAllOperations(operations.selectedOption, operations.id);})}
</form>          
{selectedOperation()}
</div>
)

这样,每个映射的操作都将id作为键。在代码中,您将传递operationsListKey作为第二个参数,这是一个函数本身,每次map函数迭代时都会返回每个操作的id。

如果有效,请告诉我。

相关内容

最新更新