【问题标题】:Function returning Promise in ternary expression not working React在三元表达式中返回 Promise 的函数不起作用 React
【发布时间】:2021-07-20 03:27:08
【问题描述】:

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

这是正确返回truefalsepermCheck() 函数:

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;
  });
}

然后在我的 react 应用程序的返回中,我尝试根据 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>

);

【问题讨论】:

  • 你有像 PROMISE 这样的表达吗?应用内容:拒绝访问。 PROMISE 不是假的(它不是未定义或 null 或 0 等),因此无论您的 permCheck 函数返回什么,它都默认为三元运算符的第一个值。
  • 您的 permCheck 函数等效于(作为返回值)函数 permCheck(res) { let isMember; return axios.get(window.location.origin + "/username").then((res) => { isMember = res.data; return isMember; }); }
  • @Virtuoz 最好的方法是什么?我不知道还有什么方法可以退货。
  • 使用状态变量(useStatethis.state)来跟踪过程,并在 promise 准备好后使用结果更新它(.then())。在那之前,渲染一些加载微调器,或者类似的东西。

标签: javascript reactjs conditional-operator


【解决方案1】:

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

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

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

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>
  )
}

【讨论】:

  • 这就是我所缺少的......非常感谢。
【解决方案2】:

我写了一个答案,因为我的评论难以辨认。 我认为你的函数permCheck 相当于

function permCheck(res) { 
  let isMember; 
  return axios.get(window.location.origin + "/username").then((res) => { 
    isMember = res.data; 
    return isMember; 
  }); 
} 

部分

axios.get(
        "https://api.endpoint.com/ismember/" +
          res.data
      )
      .then((res) => {
        return res.data; // This will be true or false
      });

对返回值没有影响。

这里是一个例子。如您所见,记录的资源是第一个而不是第二个

function permCheck(res) {
  let isMember;
  return axios.get("https://jsonplaceholder.typicode.com/todos/1").then((res) => {
    axios
      .get("https://jsonplaceholder.typicode.com/todos/2")
      .then((res) => {
        return res.data; // This will be true or false
      });
    isMember = res.data;
    return isMember;
  });
}

permCheck().then(data=>console.log(data))
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 第二个 axios.get 使用第一个中的值来调用我们使用的返回 true 或 false 的 API。那是实际上提供真/假的 axios 调用。
  • 但您没有在函数中返回该值。
  • 你不能从这样的承诺中返回一个变量!你会得到另一个承诺!
猜你喜欢
  • 2018-10-24
  • 2023-03-11
  • 2010-09-05
  • 2016-05-08
  • 2015-04-14
  • 2014-12-16
  • 2012-05-15
  • 1970-01-01
  • 2017-12-25
相关资源
最近更新 更多