javascript - Reactjs 为 render 方法定义变量的最佳策略

标签 javascript coffeescript reactjs

假设我有这段代码,它定义了组件 @authComponent取决于某些条件:

@AuthPanel = React.createClass
  componentWillReceiveProps: ->
    @authComponent =  if @props.uiState.auth_panel?.signed_in
                        <SignOutForm uiState={@props.uiState} socket={@props.socket} />
                      else
                        <SignInForm uiState={@props.uiState} socket={@props.socket} />

  render: ->
    <div className="navbar-collapse">
      {@authComponent}
    </div>

我面临的主要问题是很难理解我应该在哪里定义我的 @authComponent变量。

这是我的想法列表:

  • 我已经尝试过 componentWillMount首先,但我遇到了麻烦 - @authComponent仅调用一次。
  • 如果我尝试componentWillReceiveProps ,除了第一次之外,我将随时进行渲染。
  • 我可以尝试定义函数
  • 我可以定义@authComponent正好在 render方法,但看起来很脏。
  • 我可以使用这样的结构:{div || <SignInForm />} ,但也不太性感

有没有适当且正确的方法来定义我的组件?

最佳答案

@authComponent 放入 render() 方法中并没有什么不好和肮脏的地方。我在 GitHub 上看到了很多使用相同方法的示例。我认为在你的情况下,组件的创建不会对性能产生很大的影响,因为 React 只有在组件树中发现一些变化时才会修改 DOM。

关于javascript - Reactjs 为 render 方法定义变量的最佳策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30575095/

相关文章:

javascript - 在reactjs中渲染轮播

macos - 为什么 node.js 进程突然在 osx 上死掉,而在任何日志文件中都没有任何解释?

javascript - 评估 'this.batman()' 时,未定义不是一个函数

reactjs - eslint + jsconfig + nextjs 模块路径别名(绝对路径导入 - @)

node.js - 路线未加载组件

javascript - React-Native TouchableNativeFeedback.Ripple 不起作用

javascript - 意外的输出值即将到来

javascript - 当Api返回数据时,数据无法以 Angular 方式设置在Object的数据类型中

coffeescript - 在 CoffeeScript 中使用 Underscore.js

reactjs - 如何使用这些代码将数据放入 MuiDataTable 中?