仅当道具满足条件时才渲染

时间:2021-06-23 21:05:46

标签: javascript reactjs react-native

我是新手,这可能是一个非常愚蠢的问题,但请耐心等待。 我正在尝试通过 React Native 中的道具渲染动态对象。但是对象在渲染时并未加载到组件中。我写了一个 if 条件来满足要加载的对象,但我得到了

Error: Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null. 

我可以添加一个 else 语句,但重点是等到道具状态为“可用”。任何解释深表感谢。

render() {
    if (this.props.object?.status === 'available') {
        console.info('Log value= ', this.props);

        const path = "String" + this.props.object;
        console.info('abc =', path);

        return (
            <View
                document={path}
            />
        );
    }
}

1 个答案:

答案 0 :(得分:3)

您总是需要在 render() 函数中返回某些东西

在顶部添加一个 return null 并带有倒置的 if

  render() {
    if (this.props.object?.status !== 'available') return null;

    console.info('Log value= ',this.props);
      
    const path = "String"+this.props.object;
    console.info('abc =',path);
    
    return (
      <View
        document={path}   
        />
    );
  }