2017-06-13 16 views
0

我注意到,在編寫React組件時,我的三元表達式正在打破30-40%的時間。我不確定是否有一條規則,他們不能進入某個特定的地方或發生了什麼,因爲語法看起來對我有效。錯誤信息要麼沒有幫助,要麼我只是缺少明顯的東西。無法在React組件中編譯三元表達式

錯誤 Error 組件

class AuthContainer extends Component { 
    render() { 
    const { errorMessage, handleLogin, handleLogout, isAuthenticated } = this.props 
    return (
     { isAuthenticated 
     ? <Logout onLogoutClick={() => handleLogout()} /> 
     : <Login 
      errorMessage={errorMessage} 
      onLoginClick={(e) => handleLogin(e)} 
      /> 
     } 
    ) 
    } 
} 

isAuthenticated是一個布爾

回答

1

你並不需要使用{ ... }在那種情況下,因爲你一個JSX表達式中不是。

class AuthContainer extends Component { 
    render() { 
    const { errorMessage, handleLogin, handleLogout, isAuthenticated } = this.props 
    return (
     isAuthenticated 
     ? <Logout onLogoutClick={() => handleLogout()} /> 
     : <Login 
      errorMessage={errorMessage} 
      onLoginClick={(e) => handleLogin(e)} 
      /> 
    ) 
    } 
} 
+0

啊。這可以解釋爲什麼它有時會起作用,有時它會像這樣打破。我需要更多地關注上下文。刪除'{'的作品。謝謝! – tim5046

1

由於JSX和JS的混淆,發生了很多情況。這是我的方式。我總是把我的邏輯放在回報之外。嘗試這樣的:

class AuthContainer extends Component { 
    render() { 
    const { errorMessage, handleLogin, handleLogout, isAuthenticated } = this.props 
    const Button = (isAuthenticated)?<Logout onLogoutClick={() => handleLogout()} />:<Login 
      errorMessage={errorMessage} 
      onLoginClick={(e) => handleLogin(e)} 
      /> 
    return (
     {Button} 
    ) 
    } 
} 
+0

不錯,我很喜歡這個方法。保持回報更清潔 – tim5046