在一个简单的组件中,我有一个子组件数组。在父类的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:17:48
默认情况下,每次调用setState时,都会重新呈现所有组件和子组件。
有一个方法布尔shouldComponentUpdate(object nextProps,object nextState),每个组件都有这个方法,它负责确定“组件应该更新(运行呈现函数)吗?”每次更改状态或从父组件传递新道具时。
您可以为组件编写自己的shouldComponentUpdate方法实现,但默认实现总是返回true --意思是总是重新运行呈现函数。
默认情况下,shouldComponentUpdate总是返回true以防止状态发生变异时的细微错误,但如果您始终将状态视为不可变,并且只从渲染()中的道具和状态中读取状态,则可以使用比较旧道具和状态与替换的实现来覆盖shouldComponentUpdate。http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate
发布于 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
复制相似问题