React,动态生成选项卡时出错



我正在从这个url实现React选项卡:https://codesandbox.io/s/7mjxpo9k7x

当前代码:

<Tabs>
<div label="Gator">
See ya later, <em>Alligator</em>!
</div>
<div label="Croc">
After &apos;while, <em>Crocodile</em>!
</div>
<div label="Sarcosuchus">
Nothing to see here, this tab is <em>extinct</em>!
</div>
</Tabs>

然而,标签应该是动态的,所以我为我在本地状态下创建的一个名为"域"的数组使用map函数,如下所示:

export class AddComponent2 extends Component {
constructor(props) {
super(props)
this.state = {
domains: [],         
};
}
componentDidMount() {       
apiClient.getDomains().then(result => {
this.setState({ domains: result });
}); 
}
render() {
return (
<div>
<Tabs>
{this.state.domains.map(x =>
<div label="{x.domainCode}">
See ya later, <em>Alligator</em>!
</div>
)}
</Tabs>
</div>
)
}
}
export default AddComponent2;

然而,这会导致以下错误:

TypeError:无法读取未定义的属性"props">

this.state={activeTab:this.props.children[0].props.label,};

数组中有数据。当我对值进行硬编码时(如url上的示例所述(,我没有问题。为什么?

谢谢!

可能您的错误不是来自您过去的代码,因为您在这个代码中没有{ activeTab: this.props.children[0].props.label};

但我认为,您可以尝试获得尚未拥有的属性,因为您可以异步获得道具。所以…您应该检查何时收到响应,并在此处设置activeTab

apiClient.getDomains().then(result => {
this.setState({ domains: result, activeTab:... });
}); 

相关内容

最新更新