[英]Warning: Each child in an array or iterator should have a unique “key” prop. Check the render method of `Units`
This is only my second question here, so sorry if it's in the wrong place or has the wrong tags or anything. 这只是我的第二个问题,如果在错误的位置或带有错误的标签或其他内容,敬请原谅。
import React from 'react';
import { connect } from 'react-redux';
import { getUnits } from '../reducers/units';
import { Menu, Container, Grid, Header, Form } from 'semantic-ui-react';
class Units extends React.Component {
componentDidUpdate(prevProps) {
const { dispatch, course } = this.props
if (prevProps.course.id !== course.id)
dispatch(getUnits(course.id))
}
units = () => {
return this.props.units.map( unit =>
<ul>
<li key={unit.id}> {unit.name}</li>
<button>Edit Module Name</button>
<button>Delete Module</button>
</ul>
)
}
render() {
return (
<Container>
<Header as="h3" textAlign="center">Modules</Header>
{ this.units() }
</Container>
)
}
}
const mapStateToProps = (state) => {
return { units: state.units, course: state.course }
}
export default connect(mapStateToProps)(Units);
I'm getting the error in the title of this question even though I have keys in the li elements and they are unique. 即使我在li元素中有键并且它们是唯一的,我在此问题的标题中也遇到了错误。 I can see that they're different in the redux dev tools state, but for some reason I still get that error.
我可以看到在redux开发工具状态下它们是不同的,但是由于某些原因,我仍然会收到该错误。 I have looked at other similar errors here on stackoverflow but none of those seemed to solve this specific problem.
我在stackoverflow上查看了其他类似的错误,但是似乎没有一个可以解决此特定问题。
The answer @NorianNyx is good, basically you need to add an unique key to each component. @NorianNyx的答案很好,基本上,您需要为每个组件添加一个唯一键。 However adding a index is not a good practice as this will not represent the item every single time.
但是,添加索引不是一个好习惯,因为这不会每次都代表该项目。 If you delete or add a new item to the list the index will change.
如果删除或将新项目添加到列表中,索引将更改。
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.
选择键的最佳方法是使用一个字符串,该字符串唯一地标识其同级项中的列表项。 Most often you would use IDs from your data as keys
通常,您会使用数据中的ID作为键
So the updated solution to this will be: 因此,对此的更新解决方案将是:
return this.props.units.map((unit) => (
<ul key={unit.id}>
<li> {unit.name}</li>
<button>Edit Module Name</button>
<button>Delete Module</button>
</ul>
));
In this way your item always will have an unique id 这样,您的商品将始终具有唯一的ID
Your <ul>
component needs a key
prop. 您的
<ul>
组件需要一个key
道具。
Just change it to: 只需将其更改为:
return this.props.units.map((unit, i) => (
<ul key={i}>
<li> {unit.name}</li>
<button>Edit Module Name</button>
<button>Delete Module</button>
</ul>
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.