如果内联反应jsx,我该如何使用

时间:2017-06-17 11:20:48

标签: reactjs if-statement syntax jsx

我想在反应路由器中使用'if'来检查用户是否登录但我不知道正确的语法:

const RouteWithSubRoutes = (route) => (
  <Route exact path={route.path} render={props => (
      <route.component {...props} routes={route.routes} render = {props => (
          fakeAuth.isAuthenticated != true ? (
              <Redirect to={{
                pathname: '/signIn',
                state: { from: props.location }
          }}/>
          )
      )}/>
  )}/>
);
  

在此示例中,我想检查 fakeAuth.isAuthenticated!= true 然后重定向

2 个答案:

答案 0 :(得分:2)

为了conditionally render an element,请使用logical AND &&ternary operator,在不满足条件时返回虚假值(null,false,undefined等)。 React不会渲染空值,未定义值和假布尔值。

fakeAuth.isAuthenticated != true ? (
  <Redirect to={{
    pathname: '/signIn',
    state: { from: props.location }
  }}/>
) : null

如果您只想渲染元素 - 然后使用{condition && <Element />}语法,或者当您想根据某些条件渲染不同的组件时,请使用三元组:{condition ? <ElementA /> : <ElementB />}

const Redirect = () => <div>Redirect</div>

const TernaryExample = ({fakeAuth}) =>
<div>
{
  fakeAuth.isAuthenticated != true ? (
    <Redirect /> 
  ) : null
}
</div>

const AndExample = ({fakeAuth}) =>
<div>
{
  !fakeAuth.isAuthenticated  && <Redirect />
}
</div>

const Examples = ({fakeAuth}) =>
<div>
  <AndExample fakeAuth={fakeAuth} />
  <TernaryExample fakeAuth={fakeAuth} />
</div>
  
ReactDOM.render(
  <Examples
    fakeAuth={{isAuthenticated: false}}
  />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app" />

答案 1 :(得分:0)

您的代码很好,您忘记了其他部分。

 const RouteWithSubRoutes = (route) => (
 <Route exact path={route.path} render={props => (
  <route.component {...props} routes={route.routes} render = {props => 
 (
      fakeAuth.isAuthenticated != true ? (
          <Redirect to={{
            pathname: '/signIn',
            state: { from: props.location }
       }} />
      ) : null //here is the else.
   )}/>
 )}/>
);