【问题标题】:multiple expressions in ternary operator with react route三元运算符中的多个表达式与反应路线
【发布时间】:2020-11-21 03:34:37
【问题描述】:

嘿,我想在我的路由上设置一个会话项,这样我就可以在我的身份验证回调中使用它。所以在这里我有一个三元运算符,我检查它是否经过身份验证,然后我做一些事情,如果没有,我做两件事。

它不工作。我的问题是如何对三元运算符执行多项操作,无论它是真还是假。

<Route path="/dashboard" render={(props) => (
          auth.isAuthenticated() ? (
              <whateverComp auth={auth} {...props} />
          ) : (
              <Redirect to="/log-in"/>
          ) ? // setter for page_name
              sessionStorage.setItem('page_name', 'dashboard'): null
      )}/>

我的解决方案:

<Route path="/dashboard" render={(props) => {
        if (!auth.isAuthenticated()) {
          sessionStorage.setItem('page_name', 'dashboard');
          return <Redirect to="/log-in"/>;
        }
        else {
          return <Dashboard auth={auth} {...props} />;
        }
      }}/>

【问题讨论】:

    标签: javascript reactjs session-storage


    【解决方案1】:

    具体来说,问题在于三元运算符解析为然后由三元左侧上的任何内容评估的东西。

    例如

    const x = condition
              ? result1
              : result2;
    

    但是如果三元的左边什么都没有,除了副作用之外它什么也做不了,if 语句可以更清楚地做到这一点。 (如果你的代码比单行代码更复杂,你也应该使用if/else

    也许你想要

    if (!auth.isAuthenticated()) return (
      <whateverComp auth={auth} {...props} />
    );
    sessionStorage.setItem('page_name', 'dashboard');
    return (
      <Redirect to="/log-in"/>
    );

    【讨论】:

    • 嘿,Certian,谢谢,不,我实际上想做两件事,我想设置一个会话
    • 使用 if 语句使您的代码清晰。 (已编辑)
    【解决方案2】:
    choreDoor === 0 ? 
       (openDoor1 = botDoorPath,
        openDoor2 = beachDoorPath,
        openDoor3 = spaceDoorPath)
    : choreDoor === 1 ? 
       (openDoor2 = botDoorPath,
        openDoor1 = beachDoorPath, 
        openDoor3 = spaceDoorPath) 
    : choreDoor === 2 ?
       (openDoor3 = botDoorPath,
        openDoor1 = beachDoorPath, 
        openDoor2 = spaceDoorPath)
    : false;
    

    解决了我的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2019-02-10
      • 2012-09-02
      • 1970-01-01
      • 2018-11-19
      相关资源
      最近更新 更多