常常写react代码,一不小心就会报如下错误,
1 2 3 |
Warning: Each child in a list should have a unique "key" prop. Check the render method of <code>ProductTable</code>. See https://fb.me/react-warning-keys for more information. |
解决警告Warning: Each child in a list should have a unique key prop.
基本都是因为在循环生成多个组件的时候,没有给组件加上key引起的,因为dom进行diff对比 没有key值,所以报错警告。。 此时我们需要循环生成多个组件中,加上key值(唯一值)那么就不会报错了,虽然不起眼的bug,但是特别容易范这类低级失误 例如如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Html = () => { const data = [3, 6, 9, 12, 24, 36]; const html = []; data.forEach(item => { html.push( // 生成组件时带上key值 <div className={styles.productWrap} key={item}> <div className={styles.leftLable}>{item}期:</div> <InputNumber /> </div> ); }); return html; }; |