React 子渲染函数中的早期 returns:return 空、[] 或 React.Fragment?

Early returns in React sub render function: return null, [], or React.Fragment?

假设我有一个可能会或可能不会呈现计数器的简单组件。

在 React 中表达阻塞代码路径的最佳实践是什么?应该 return null[] 还是 Fragment

class App extends Component {
  renderCounter() {
    if (!this.props.shouldRenderCounter) {
      // // which should I return?
      // return; 
      // return null; 
      // return []; 
      // return <React.Fragment />; 
    }
    return <Counter />;
  }

  render() {
    return (
      <div>
        {this.renderCounter()}
      </div>
    );
  }
}

我认为 null 是最清晰的,但我可以想象如果 return 函数周围的上下文需要一个组件,它会导致问题。 []Fragment 对我来说都是不错的选择,除了 Fragment 更容易阅读。有什么区别?

您不需要为其创建额外的函数。

这将完成工作:

class App extends Component {
  render() {
    return (
      <div>
        {this.props.shouldRenderCounter && <Counter />}
      </div>
    );
  }
}

返回 nullrecommended by the React team:

In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.