首页 > 解决方案 > 在三元表达式中返回 Promise 的函数不起作用 React

问题描述

我有一个调用的函数permCheck(),它将根据某些逻辑解析为真或假。我需要从中获取值并在三元表达式中使用它来更改用户看到的内容。然而,它似乎总是返回表达式的真部分,即使permCheck()是假的。

这是正确返回or的permCheck()函数:truefalse

function permCheck(res) {
  let isMember;
  return axios.get(window.location.origin + "/username").then((res) => {
    axios
      .get(
        "https://api.endpoint.com/ismember/" +
          res.data
      )
      .then((res) => {
        return res.data; // This will be true or false
      });
    isMember = res.data;
    return isMember;
  });
}

然后在返回我的反应应用程序时,我试图根据permCheck函数更改内容。这似乎总是默认为三元表达式的第一部分。如您所见,我什console.log至在三元表达式中有一个正确返回真或假的表达式。

return (
<div className="ui">
  <AppLayout
    content={
      permCheck().then((a) => {
        console.log("IN TERNARY: " + a);
        Promise.resolve(a);
      })
        ? appContent
        : accessDenied
    } // Here we expect true or false from permCheck()
    navigation={<ServiceNavigation />}
    notifications={<FlashMessage />}
    breadcrumbs={<Breadcrumbs />}
    contentType="table"
    tools={Tools}
    headerSelector="#navbar"
    stickyNotifications={true}
  />
</div>

);

标签: javascriptreactjsconditional-operator

解决方案


你不能检查一个你只会在未来收到的值,所以你不能只是打开你的承诺。

相反,您应该使用状态变量来存储结果,并在组件可用时重新渲染它。在此之前,您可以渲染一些加载效果/微调器/文本,以通知用户。

假设您使用的是功能组件,它看起来像这样:

function component(){
  const [permission, setPermission] = useState(undefined)
  //Use `useEffect` to prevent recurring checking
  useEffect(() => {
    permCheck().then((a) => {
      //Update (rerender) the component with the permission info
      setPermission(a)
    })
  }, [])
  return (
  <div className="UI">
    <AppLayout
      content={
        //When this runs for the first time, `permission` will be `undefined` (meaning 'not available'), so handle this case as well:
        permission === undefined
          ? 'Checking permission, hang on...'
          : permission
            ? appContent
            : accessDenied
      }
      navigation={<ServiceNavigation />}
      notifications={<FlashMessage />}
      breadcrumbs={<Breadcrumbs />}
      contentType="table"
      tools={Tools}
      headerSelector="#navbar"
      stickyNotifications={true}
    />
  </div>
  )
}

推荐阅读