我正在优化部分,发现部分列表正在渲染子组件,即使它们没有变化。在研究中,我发现你必须传递一个唯一标识一个部分的键,以避免重新渲染子组件。
我确实将唯一键传递给子组件,但即使它被重新渲染。
更新:下面的代码
我正在使用 react-redux 进行状态管理。
使成为:
<SectionList
renderItem={this.renderItem}
renderSectionHeader={this.renderSectionHeader}
sections={this.getSectionListData()}
keyExtractor={(item, index) => item + index}
/>
渲染项:
if (conditionX)
return <XComponent data={this.getDataX()} action={this.doSomethingToX} />
else if (conditionY)
return <YComponent data={this.getDataY()} action={this.doSomethingToY} />
else if (conditionZ)
return <ZComponent data={this.getDataZ()} action={this.doSomethingToZ} />
else
return <View/>
getDataX = () => return this.props.reduxState.dataX;
getDataY = () => return this.props.reduxState.dataY;
getDataZ = () => return this.props.reduxState.dataZ;
doSomethingToX/Y/Z : Updates the reducer values X/Y/Z respectively.
最初我在 reducer 中没有任何 X/Y/Z 值,但如果我更新值 X,子组件(即YComponent
, ZComponent
)也会重新渲染。
关于如何避免这种不必要的渲染的任何建议。