在React中遇到了两个具有相同密钥的孩子

时间:2018-08-15 13:16:10

标签: reactjs semantic-ui solidity next.js

我目前正在尝试学习如何创建一个Web应用程序以与我编写的以太坊合约进行交互。因此,我选择学习如何使用React和Semantic-UI。

我正在处理的页面无法正常工作。由于我不理解的错误,它没有显示CardGroup:

warning.js?040ca1d:33 Warning: Encountered two children with the same key, `-`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
    in div (created by CardGroup)
    in CardGroup (at index.js?entry:30)
    in div (at index.js?entry:37)
    in div (at Layout.js:5)
    in Unknown (at index.js?entry:36)
    in BiddingCreator (created by Container)
    in AppContainer (created by Container)
    in Container (created by App)
    in div (created by App)
    in App

这是我当前的代码:

import React, {Component} from 'react';
import biddingCreator from '../Ethereum/BiddingCreator';
import {Card} from 'semantic-ui-react';
import Layout from '../components/Layout'

const compiledBidding = require('../Ethereum/build/Bidding.json');

class BiddingCreator extends Component{

  static async getInitialProps(){
    const biddings = await biddingCreator.methods.getBiddings().call();

    const items = await biddings.map( async address => {
      var summary = await biddingCreator.methods.viewBidding(address).call();
      console.log(summary);
      console.log(address);
      return {
        header: address,
        description: summary[1],
        meta: address,
        fluid: true
      };

    });

    return { biddings, items};
  }

 renderBiddings(){
    console.log(this.props.items);
    return <Card.Group items={this.props.items} />;
}

  render(){

    return(
      <Layout>
       <div>

    {this.renderBiddings()}
    </div>
    </Layout>
  )
  }
}

export default BiddingCreator;

有人可以向我解释我做错了什么,这个错误意味着什么吗?

2 个答案:

答案 0 :(得分:3)

这是React lists and keys

的常见错误

我已经检查了Card.Group的语义用户界面反应源代码,看来您可以为每个项目添加key属性,例如

const items = this.props.biddings.map(async (address, index) => {
  var summary = await biddingCreator.methods.viewBidding(address);
  return {
    key: index,
    header: summary[0],
    description: summary[1],
    meta: address,
    fluid: true
  };
});

PS

这是Card.Group生成密钥const key = item.key || [item.header, item.description].join('-')

的方式

在某些情况下,headerdescription的值似乎为空,这就是为什么您会遇到错误“遇到两个具有相同键-的孩子”的原因

答案 1 :(得分:0)

这是我在yuyokk的帖子中使用帮助找到的解决方案:

当我的车试图渲染,因此您没有数据,因此也没有密钥时,项目仍在等待其承诺。

使用此代码,现在可以使用:

const items =await Promise.all( biddings.map(async address => {

      var summary = await biddingCreator.methods.viewBidding(address).call();
      return {
        header: summary[0],
        description: summary[1],
        meta: address,
        fluid: true
      };
    }));