在React Native中使用条件呈现的最佳方法
问题描述:
我正在使用React Native应用程序。在应用程序中,当用户登录时,会向服务器发出API调用,以使用redux-saga来获取数据。在redux存储中,我维护一个布尔变量“fetchingData”。一旦API调用被启动,它被设置为'true'并且一旦数据被提取或发生一些错误,就被设置为'false'。现在,我想在数据被提取时显示一个微调,并在数据被提取时显示一个FlatList。我知道我可以通过将return语句包装进if-else条件来做到这一点。我想应该有一些更好的方法来做到这一点。 如果有人能帮助我,请告诉我一种在React Native中实现这种有条件呈现的好方法。先谢谢你。在React Native中使用条件呈现的最佳方法
答
我不这么认为。当调用render()
方法时,适当的组件需要是基于状态返回的。
render() {
const isLoading = this.state.isLoading
return isLoading ?
<Spinner /> //return a spinner
:
<FlatList /> return a list with data
}
答
如果这是你到处使用有几种方法来抽象图案了一个模式:
-
创建一个通用
<Loading />
组件:class Loading extends React.Component { static defaultProps = { waitingElement: <Spinner />, renderedElement: null }; render() { return this.props.loading ? this.props.waitingElement : this.props.renderedElement; } } // In some other component's `render`: <Loading renderedElement={<component with=props />}, loading={this.state.isWaiting} />
-
使用higher-订购组件来包装您的组件:
function withLoading(Component, spinner = <Spinner />) { return class extends Component { render() { if (this.props.loading) return spinner; return super.render(); } }; } // Some other file completely export default withLoading(class MyComponent { render() { return "Happy path only!"; } });