Reactjs 如何向组件对象添加键

Reactjs 如何向组件对象添加键,reactjs,ecmascript-6,Reactjs,Ecmascript 6,我正在尝试制作树型HTML。(带React) 这是节点类,它包含子节点 class Node extends React.Component { constructor(props) { super(props); this.state = { children: [] }; } render() { return <div id={this.props.id} classNa

我正在尝试制作树型HTML。(带React)

这是节点类,它包含子节点

class Node extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            children: []
        };
    }

    render() {
        return <div id={this.props.id} className="person">
                   <div className="info">
                       <div className="name">{this.props.name}</div>
                   </div>
                   <div className="childrenWrap">
                       <div className="children">
                           {this.state.children}
                       </div>
                   </div>
               </div>;
    }

    addChild(node) {
         this.setState({children: this.state.children.concat(node)});
    }
}

//////////////

let tree = document.querySelector("#tree");
let root = ReactDom.render(<Person id="root" name="A" />, tree);
root.addChild(<Person id="child1" name="B" />);
root.addChild(<Person id="child2" name="C" />);
root.addChild(<Person id="child3" name="D" />);
类节点扩展React.Component{
建造师(道具){
超级(道具);
此.state={
儿童:[]
};
}
render(){
返回
{this.props.name}
{this.state.children}
;
}
addChild(节点){
this.setState({children:this.state.children.concat(node)});
}
}
//////////////
let tree=document.querySelector(“树”);
让root=ReactDom.render(,tree);
root.addChild();
root.addChild();
root.addChild();
但是,此代码将出现警告“数组或迭代器中的每个子级都应该有一个唯一的“key”prop”

因此,我添加了
key={this.props.id}
id={this.props.id}

但它没有解决我如何解决这个问题?

问题不在于父组件,而在于子组件

这可能会解决问题:

root.addChild(<Person id="child1" key="child1" name="B" />);
root.addChild(<Person id="child2" key="child2" name="C" />);
root.addChild(<Person id="child3" key="child3" name="D" />);
root.addChild();
root.addChild();
root.addChild();

但在我看来,您正在以一种非常糟糕的方式处理问题-您不应该将整个渲染元素保持在
状态
,只保留渲染它们所需的数据,然后在
渲染
中创建树

问题不在于父组件,而在于子组件

这可能会解决问题:

root.addChild(<Person id="child1" key="child1" name="B" />);
root.addChild(<Person id="child2" key="child2" name="C" />);
root.addChild(<Person id="child3" key="child3" name="D" />);
root.addChild();
root.addChild();
root.addChild();

但在我看来,你是在以一种非常糟糕的方式处理这个问题-你不应该将整个渲染元素保持在你的
状态
,只需要渲染它们所需的数据,然后在
渲染
中,你应该创建树

你的键只需要是唯一的;为什么不将其设置为id的值

root.addChild();

您的密钥只需要是唯一的;为什么不将其设置为id的值

root.addChild();

OP说是他做的,但似乎他把
key
放在了错误的组件上OP说是他做的,但似乎他把
key
放在了错误的组件上那么添加child的最佳方法是什么呢?@WebEngine通过传递数据结构,例如
[{id:“child1”,name:“B”},{id:“child2”,name:“C”},{id:“child3”,name:“D”}]
然后基于此数据呈现子项然后添加子项的最佳方法是什么?@WebEngine通过传递数据结构,例如,
[{id:“child1”,name:“B”},{id:“child2”,name:“C”},{id:“child3”,name:“D”}]
然后基于此数据呈现子项