Reactjs 为渲染方法定义变量的最佳策略
Reactjs best strategy to define a variable for render method
假设我有这段代码,它根据某些条件定义了组件@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
,除了第一次之外,我将始终获得渲染。
- 我可以尝试定义函数
- 我可以在
render
方法上准确定义 @authComponent
,但它看起来很脏。
- 我可以使用这样的构造:
{div || <SignInForm />}
,但它也不性感
是否有任何适当和正确的方法来定义我的组件?
将 @authComponent
放在 render()
方法中并没有什么不好和肮脏的地方。我在 GitHub 上看过很多使用相同方法的示例。在我看来,组件的创建不会对你的性能产生太大影响,因为 React 只会在组件树中发现一些变化时才会修改 DOM。
我认为这个解决方案更好:
@AuthPanel = React.createClass
getAuthComponent: ->
if @props.uiState.auth_panel?.signed_in
return <SignOutForm uiState={@props.uiState} socket={@props.socket} />
else
return <SignInForm uiState={@props.uiState} socket={@props.socket} />
render: ->
<div className="navbar-collapse">
{@authComponent()}
</div>
我在那里找到了它:https://github.com/planningcenter/react-patterns#sub-render
假设我有这段代码,它根据某些条件定义了组件@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
,除了第一次之外,我将始终获得渲染。 - 我可以尝试定义函数
- 我可以在
render
方法上准确定义@authComponent
,但它看起来很脏。 - 我可以使用这样的构造:
{div || <SignInForm />}
,但它也不性感
是否有任何适当和正确的方法来定义我的组件?
将 @authComponent
放在 render()
方法中并没有什么不好和肮脏的地方。我在 GitHub 上看过很多使用相同方法的示例。在我看来,组件的创建不会对你的性能产生太大影响,因为 React 只会在组件树中发现一些变化时才会修改 DOM。
我认为这个解决方案更好:
@AuthPanel = React.createClass
getAuthComponent: ->
if @props.uiState.auth_panel?.signed_in
return <SignOutForm uiState={@props.uiState} socket={@props.socket} />
else
return <SignInForm uiState={@props.uiState} socket={@props.socket} />
render: ->
<div className="navbar-collapse">
{@authComponent()}
</div>
我在那里找到了它:https://github.com/planningcenter/react-patterns#sub-render