【发布时间】:2018-12-16 06:32:01
【问题描述】:
假设我的页面中有 10 个或更多组件,现在每当我使用 setState 更改状态时,react native 会重新渲染所有组件(更改的组件和所有其他实际上不需要更改的组件)。
如何让 react native 只重新渲染一些受状态改变影响的组件?我在某处读到你可以使用 key props 来做到这一点,但没有关于如何做的例子。
export default class MyApp extends React.Component({
constructor(props) {
super(props);
this.state = {
result: ''
}
}
LoadChild() {
// Some functions that load a tabnavigator component
}
render() {
return(
<View style={{ flex: 1}}>
<ParentComponent>
<Text>
//Some Text that need to be updated
{ this.state.result }
</Text>
<ChildComponent>
{ this.LoadChild() }
</ChildComponent>
</ParentComponent>
</View>
);
}
});
每当我调用像 setState({ result: 'test' }) 这样改变状态的函数时,我需要 ParentComponent 中的文本重新渲染以显示当前状态,但这也会导致 ChildComponent 重新渲染,导致函数LoadChild() 再次触发,因此 componentDidMount() 也再次触发。我希望状态仅在状态更改时影响 ParentComponent 中的文本。
【问题讨论】:
标签: javascript reactjs react-native rerender