在我的主应用程序渲染功能中... 我生成了这个列表。
const buildings = this.state.buildings.map(buildingData=>
{
console.log("unique id is:", buildingData.id)
return(
<Building
key={buildingData.id}
name ={buildingData.name}
handleBuildingBuy={this.handleBuildingBuy}
buyPrice={buildingData.buyPrice}
count = {buildingData.count}
subjectsOfIncrease = {buildingData.subjectsOfIncrease}
isBuyable = {buildingData.isBuyable}
isUnlocked = {buildingData.isUnlocked}
/>)
});
但我还是得到了控制台的输出错误,即使每个键都是定义的并且是唯一的......
App.js:224 unique id is: 0
App.js:224 unique id is: 1
App.js:224 unique id is: 2
App.js:224 unique id is: 3
App.js:224 unique id is: 4
App.js:224 unique id is: 5
App.js:224 unique id is: 6
App.js:224 unique id is: 7
index.js:1 Warning: Each child in a list should have a unique "key" prop.
Check the render method of `Building`. See react-warning-keys for more information.
in div (at Building.js:11)
in Building (at App.js:226)
in div (at App.js:275)
in div (at App.js:274)
in App (at src/index.js:8)
更奇怪的是,我有一个类似的循环来处理其他的事情,其中键没有表现得很奇怪。
const resources = this.state.resources.map(resourceData=>
{
console.log("unique resourceName is:", resourceData.name)
return(
<Resource
name ={resourceData.name}
max = {resourceData.max}
isUnlocked = {resourceData.isUnlocked}
changePerTick = {resourceData.changePerTick}
amount={resourceData.amount}
key={resourceData.name} //change out to a number - names are in fact unique.
/>)
});
而那个输出是。
unique resourceName is: grey
App.js:240 unique resourceName is: red
App.js:240 unique resourceName is: green
App.js:240 unique resourceName is: blue
App.js:240 unique resourceName is: purple
App.js:240 unique resourceName is: teal
App.js:240 unique resourceName is: orange
所以我不明白为什么上面的代码不能用,而下面的代码却能用。
谁能告诉我可能发生了什么?
编辑:如果它是相关的,建筑组件。
function Building(props)
{
if(props.isUnlocked)
{
const buyClass = props.isBuyable ? "afford": "cantAfford";
const PriceList = props.buyPrice.map(price=>
{
return(
<div>
{price.name}: {price.cost}
</div>
)
})
return(
<div className="building">
<div className="buildingTitle"> BUY FOR:
<div className={buyClass}>{PriceList}</div>
</div>
<div className="buildingBuyContainer">
{props.isBuyable ?
<button name={props.name} onClick={props.handleBuildingBuy} className="buildingBuyBTN">{props.name}</button>
:
<button name={props.name} className="buildingNoBuyBTN">{props.name}</button>
}
</div>
<div className="counter"> COUNT:{props.count}
</div>
</div>
)
}
else{return null}
}
你的错误确实是在建筑中。你没有向PriceList添加键。这需要一个键
const PriceList = props.buyPrice.map(price=>
{
return(
<div>
{price.name}: {price.cost}
</div>
)
})
它给你的错误是把你指向了正确的地方。
正如错误信息所显示的那样,问题出在您的内部。<Building>
组件的渲染方法。
检查一下这个组件的渲染方法
Building
.
它甚至告诉你在哪里。
在div中(在Building.js:11)
不过英勇的调试工作!
eta: 如果你的 buyPrice
数组不会改变,修复方法很简单。
const PriceList = props.buyPrice.map((price,index)=>
{
return(
<div key={index}>
{price.name}: {price.cost}
</div>
)
})