【问题标题】:Best way to use conditional rendering in React Native在 React Native 中使用条件渲染的最佳方式
【发布时间】:2017-09-04 11:26:39
【问题描述】:

我正在开发一个 React Native 应用程序。在应用程序中,当用户登录时,会对服务器进行 API 调用,以使用 redux-saga 获取数据。在 redux 商店中,我正在维护一个布尔变量“fetchingData”。一旦 API 调用开始,它就设置为“真”,一旦获取数据或发生某些错误,它就设置为“假”。现在,我想在获取数据时显示一个微调器,并在获取数据时显示一个 FlatList。我知道我可以通过将 return 语句包装到 if-else 条件中来做到这一点。我想必须有一些更好的方法来做到这一点。 如果有人可以帮助我,请告诉我在 React Native 中实现这种条件渲染的好方法。提前谢谢你。

【问题讨论】:

    标签: reactjs react-native redux redux-saga


    【解决方案1】:

    如果这是您在任何地方都使用的模式,那么有几种方法可以将模式抽象出来:

    1. 创建一个通用的<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} />
      
    2. 使用高阶组件来包装你的组件:

      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!";
        }
      });
      

    【讨论】:

      【解决方案2】:

      我不这么认为。当render() 方法被调用时,需要根据状态返回相应的组件。

      render() {
          const isLoading = this.state.isLoading
          return isLoading ?
              <Spinner /> //return a spinner
              :
              <FlatList /> return a list with data
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-15
        • 2018-03-18
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-10
        • 2018-04-03
        相关资源
        最近更新 更多