繁体   English   中英

在react或react-native中处理渲染函数中的多个返回的正确方法是什么

[英]What is the right way to handle multiple returns in a render function in react or react-native

我在使用expo的react-native中具有以下组件:

import React, { Component } from 'react';
import { Text, View, ActivityIndicator } from 'react-native';
import { Location, Permissions } from 'expo';

export default class WeatherReport extends Component {

  state = {
    grantedLocationPermission: '',
    location: null,
  }

  componentDidMount() {
    Location.requestPermissionsAsync();
    Permissions.getAsync(Permissions.LOCATION)
      .then(({ status }) => {
        this.setState({
          grantedLocationPermission: status,
        })
      })
      .catch((error) => {
        console.warn(error);
        this.setState({
          grantedLocationPermission: 'undetermined'
        })
      })
  }

  render() {
    if(this.state.grantedLocationPermission === 'granted') {
      return (
        <View>
        <Text>Welcome to Weatheru!</Text>
        </View>
      )
    } else if(this.state.grantedLocationPermission === 'denied' || this.state.grantedLocationPermission === 'undetermined') {
      return (
        <View>
          <Text>Permission denied!</Text>
        </View>
      )
    } else {
      return (
        <View>
          <ActivityIndicator size={100} color="#5D50FE" />
        </View>
      )
    }
  }
}

render()有三个返回值,其中两个返回此this.state.grantedLocationPermission特定值的this.state.grantedLocationPermission 但是,当此组件首次加载this.state.grantedLocationPermission = ''它将重新呈现为特定值。 结果,我使用了ActivityIndicator (简单的加载器)来显示所有其他条件的加载动画。

这是正确的方法吗? 或者,还有更好的方法?

您可以创建状态到组件的映射,还可以创建默认/后备处理程序。 就像是:

const Denied = () => <Text>Permission Denied!</Text>;
const DefaultHandler = () => <ActivityIndicator size={100} color="#5D50FE" />;

const handlers = {
  granted: () => <Text>Welcome to Weatheru!</Text>,
  denied: Denied,
  undetermined: Denied,
}

const Cmp = handlers[this.state.grantedLocationPermission] || DefaultHandler;

return (
  <View>
    <Cmp />
  </View>
);

您所做的没有 有用。

但是,应用一些通用的编程最佳实践将以多种方式提高可读性和可维护性。

为每种情况建立一个单独的组件,更严格地遵循单一责任原则

  1. 大大降低了WeatherReport组件的render方法的复杂性,使其更易于阅读和推理。

  2. 无需为每种情况重复<View>容器。 如果您决定更换容器,则只需要在一个地方进行即可。 不要重复自己 ,避免重复代码等)

  3. 允许您单独更改每种情况的行为或输出,而不必在WeatherReport的render方法中一堆条件渲染逻辑中摸索。 这些组件中的每一个都可以移至其自己的单独文件中,以供重复使用和/或实现更复杂的行为而不会污染WeatherReport组件。

    假设您需要显示“权限被拒绝!” 在整个应用中的许多地方,然后您决定需要将其更改为“未经授权!” 或者您需要多语种支持,并且需要说“祖康Verweigert!” 针对特定的语言环境。 如果您只有一个组件可以在您的应用程序需要的任何地方呈现它,则修改该组件可以在任何地方修复它。

  4. 使将来更容易支持其他状态。 假设您的权限变得比授予/拒绝的权限更详细; 也许您具有管理功能,或者只允许查看报告的特定部分。 添加admin: AdministratorViewrestricted: RestrictedView非常简单,根本不会使基本组件的渲染逻辑复杂化。

同样,从功能上讲,这也可以做同样的事情,但是如果您的应用程序变得最复杂,那么就需要事先考虑这些事情并进行相应的编码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM