坚持“阵列中的每个孩子或迭代器都应该有一个独特的”关键“道具”

时间:2017-09-27 14:47:51

标签: reactjs

我知道这意味着什么,并且通过为子项设置唯一ID多次解决了这个问题,但这次它仍然抛出相同的异常,我无法理解为什么

这是代码;

    render() {
     question.Choices = this.appState.question.Choices.map((value, index) => {
            if (typeof value == "string")
              return (<SQcomponent index={index} value={question.Number + "-" + index} text={value} checkedHandler={this.choiceChecked} />)
    })
    return (<div> {question.Choices} </div>)
  }
}


    class SQcomponent extends Component {
      constructor(props) {
        super(props)
      }
      render() {
        return (<div key={this.props.index} className="checkbox checkbox-circle">
          <input id={this.props.index} name={this.props.index} type="checkbox" value={this.props.value} />
          <label htmlFor={this.props.index}>
            {this.props.text}
          </label>
        </div>)
      }
    }

当我启动应用程序时,它工作正常,但这个消息让我烦恼; enter image description here

1 个答案:

答案 0 :(得分:2)

您需要将密钥放在地图中的组件上:

    render() {
     question.Choices = this.appState.question.Choices.map((value, index) => {
            if (typeof value == "string")
              return (<SQcomponent key={index} index={index} value={question.Number + "-" + index} text={value} checkedHandler={this.choiceChecked} />)
    })
    return (<div> {question.Choices} </div>)
  }
}


但是,您应该使用 index 以外的值作为密钥。

  

当您没有渲染项目的稳定ID时,您可以使用   项目索引作为最后手段的关键:

https://facebook.github.io/react/docs/lists-and-keys.html