每个孩子都应该有道具警告



当我在映射函数中添加键时,为什么会收到这个警告:Each child in a list should have a unique "key" prop.

const fieldsArr =
effectsTextArr.map((effectsText, i) => {
const style = effectsText.length === 1 ? fieldStyle1Icon : fieldStyle2Icons
return (
<div style={style} key={i} onClick={() => playerStateContext.handleClickOnRelic(effectsArr[i], i)}>
{playerState.relics[i] ? effectsText : <Shiny/>}
</div>
)
}
)

源阵列:

const effectsTextArr = [
[<Jewel/>],
[<Jewel/>],
[<Coin/>, <div style={overLapStyle}><Weapon/></div>],
[<Weapon/>],
[<Explore/>, <div style={overLapStyle}><Text/></div>],
[<Coin/>, <div style={overLapStyle}><Text/></div>],
[<Coin/>],
[<Explore/>],
[<Draw1Card/>]
]

我是否也应该向源数组元素添加键?这样使用JSX元素是错误的吗?我用它们来存储我在应用程序的不同位置使用的图标。

effectsText是JSX元素的数组,它仍然需要为其分配一个唯一的密钥。

{playerState.relics[i] ? 
effectsText :  // here an array is passed and every elem requires a key
<Shiny />
}

因此,您可以映射它并分配一个密钥,而不是直接将其作为变量传递:

{effectsText.map((nested) => (
<React.Fragment key={someUniqId}>{nested}</React.Fragment>
)}

相关内容

最新更新