在 React 中有一种方便的列表生成方式:
userList.map((user, idx) => {
<UserListItem id={idx} user={user} />;
});
但是如果直接这么写,会在 f12
调试的时候看到下面这样的报错:
warning: each child in a list should have a unique "key" prop.
我们需要设置 key 这个字段,具体原因参考 Reference
Reference
为什么需要设置 key: https://juejin.cn/post/6940974776441634823
有关设置 key 的报错: https://bobbyhadz.com/blog/react-key-is-not-a-prop-trying-to-access-it-results-undefined
React uses props like
key
andref
internally, so it doesn’t forward them to the component and trying to access these props returnsundefined
.