javascript - 在三元表达式中返回 Promise 的函数不起作用 React
问题描述
我有一个调用的函数permCheck()
,它将根据某些逻辑解析为真或假。我需要从中获取值并在三元表达式中使用它来更改用户看到的内容。然而,它似乎总是返回表达式的真部分,即使permCheck()
是假的。
这是正确返回or的permCheck()
函数:true
false
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>
);
解决方案
你不能检查一个你只会在未来收到的值,所以你不能只是打开你的承诺。
相反,您应该使用状态变量来存储结果,并在组件可用时重新渲染它。在此之前,您可以渲染一些加载效果/微调器/文本,以通知用户。
假设您使用的是功能组件,它看起来像这样:
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>
)
}
推荐阅读
- html - 如何将此图像的一部分隐藏在其他元素后面?
- ios - 返回复合代码时出错 - Google Places Swift
- python - Jupyter 仪表板扩展中的单元格不可读/不可编辑
- r - 在 ggplot 中绘制自定义图例
- javascript - 下一个 router.useRouter 甚至不是一个模拟 RouterContext 的函数
- r - 使用 str_detect 的 stringr 包 - 搜索一个单词并排除单词
- docker - 如何将 docker 启动脚本转换为 supervisord.conf 文件?
- redux - 为什么中间件转换后的 createAsyncThunk.fulfilled 操作负载没有在 Thunk 调用点转换?
- database - 防止多对多表中的“重复”行
- python - 在同一模板中使用 CreateView 和 ListView 并正确使用 form.instance