在一个简单的组件中,我有一个子组件数组。在父类的state中(除其他外),我持有一个对象数组,在render函数中,我将子组件构造为:
const children = [];
let i = 1;
for(let child of this.state.children){
children.push(<Decoration key={i++} {...child} />);
}
return (
<div>{children} {this.state.something_else}</div>
);问题是,每当我更改其他状态值时,子组件的呈现函数就会被调用,这很奇怪,因为我不改变children数组中的任何内容。有什么想法吗?这段代码效率低下吗?
发布于 2017-06-07 13:18:27
您可能希望将代码从render()方法中移出,并将其放入生命周期方法之一--在本例中,它将是
componentWillMount和componentWillReceiveProps.您可以在那里构造children数组,只需在render()中显示它。
render(){
return (
<div>{children} {this.state.something_else}</div>
);
}https://stackoverflow.com/questions/44413719
复制相似问题