【问题标题】:React JS Best PracticeReact JS 最佳实践
【发布时间】:2019-02-19 13:38:31
【问题描述】:

我打算使用我的状态作为一种信号形式,表明我将来回更改以显示我的加载屏幕、主窗体以及成功或错误消息。但不确定这是否是最佳做法。这是一个示例代码

div hidden={this.state.FormStatus.statusMode !== "Loading"}>
          <LoadingScreen />
        </div> 

div hidden={this.state.FormStatus.statusMode !== "Main"}>
          <MainForm/>
        </div> 

但我不确定这是否是最好的方法,我担心它会减慢我的应用程序或用这个方法吃掉我的客户 CPU。你能推荐更好的方法吗?

【问题讨论】:

标签: reactjs


【解决方案1】:
render() {
  const { statusMode } = this.state.FormStatus;

  if (statusMode === 'Loading') {
    return <LoadingScreen />;
  } else if (statusMode === 'Main' {
    return <MainForm />;
  }
}

render() {
  const { statusMode } = this.state.FormStatus;

  return (
    <div>
      <span>Something you want to display no matter what</span>
      {statusMode === 'Loading' && <Loading />}
      {statusMode === 'Main' && <Main />}
    </div>
  );
}

【讨论】:

  • 这真是太好了,我试试吧。
【解决方案2】:

不确定性能改进如何超过你正在做的,但这里有一个想法。

render() {
  const { FormStatus: { statusMode } } = this.state;
  const component = { Loading: <LoadingScreen />, Main: <MainForm /> };

  return component[this.state.FormStatus.statusMode];
}

为了记录,你所做的很好。唯一真正的改进是只渲染一个div 而不是两个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2022-06-15
    • 2018-09-05
    相关资源
    最近更新 更多