// This is my routes which I'm trying to map through
const Header = () => {
const routes = [
{ id: 1, name: 'Home', link: '/' },
{ id: 2, name: 'Blogs', link: '/blogs' },
{ id: 3, name: 'Contact', link: '/about' }
];
//Since providing index as key prop is not good I'm giving uuidv4() as key prop
{
routes.map(route =>
<li className='mr-8'>
<NavLink className='px-2' style={navLinkStyles} key={uuidv4()} to={route.link}>{route.name}</NavLink>
</li>
)
}
这是我在控制台中收到的警告:
react_devtools_backend.js:3973 Warning: Each child in a list should have a unique "key" prop.
Check the render method of `Header`. See https://reactjs.org/link/warning-keys for more information.
at li
at Header (http://localhost:3000/static/js/bundle.js:3874:98)
at div
at App
at Router (http://localhost:3000/static/js/bundle.js:90278:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:89087:5)
证明索引作为 key prop 也会给出相同的警告和 uuidv4() 。在这种情况下我应该给出什么作为关键支撑?
您的路线有 ID,它们看起来是特定路线的唯一标识符(
link
也可能有效),因此请使用它。不要使用 uuid(或 Math.random
)作为键(除非你确实没有其他方法来识别被映射的元素),并将键放在从回调直接返回的元素上。
routes.map(route =>
<li className='mr-8' key={route.id}>
<NavLink className='px-2' style={navLinkStyles} to={route.link}>{route.name}</NavLink>
</li>
)
确实如此,如果您确实没有办法识别元素,您可以使用 UUID 库 和
之间的混合策略export const getUniqueId = () => {
return `${uuidv4()}-${generateUniqueStringWithTimestamp()}`;
}
时间戳
export const generateUniqueStringWithTimestamp = () => {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hour = String(now.getHours()).padStart(2, '0');
const minute = String(now.getMinutes()).padStart(2, '0');
const second = String(now.getSeconds()).padStart(2, '0');
const miliseconds = String(now.getMilliseconds());
return `${year}${month}${day}${hour}${minute}${second}${miliseconds}`;
}
你会得到类似这样的“4f6fdbc1-2c5d-4e64-a9e1-99878ff68e58-20230512113800865”
请记住,使用 UUID 库,您可以提供重复项,因此使用此策略,您将降低错误的可能性
如果数组中没有值用作键,这个答案中提出的解决方案就像一个魅力:
...
routes.map(route =>
<li className='mr-8' key={JSON.stringify(route)}>
...