英文:
Function doesn't return true or false ReactJS
问题
当我调用我的permissionCheck
函数时,它不会返回true
或false
。
permissions
状态是完整的。
这是我的代码部分:
const [permissions, setPermissions] = useState({});
const permissionCheck = (permission) => {
var i;
for (i = 0; i < permissions.length; i++) {
if (permissions[i].name === permission) {
return false;
} else if (permissions[i].name !== permission) return true;
}
}
// 结果将设置在隐藏组件上。如果结果为true,它将被隐藏,如果为false,它将被显示
hidden={permissionCheck('TEST')}
英文:
When I call my permissionCheck it doesn't return true or false.
The permissions useState is full.
This is the part of my code:
const [permissions, setPermissions] = useState({});
const permissionCheck = (permission) =>
{
var i;
for (i = 0; i < permissions.length; i++)
{
if (permissions[i].name === permission)
{
return false;
} else if (permissions[i].name !== permission) return true;
}
}
// the outcome will be set on the hidden component. So if the outcome is true it will be hidden and if it is false it will be shown
hidden={permissionCheck('TEST')}
答案1
得分: 0
更改代码如下:
const permissionCheck = (permission) => {
var i;
for (i = 0; i < permissions.length; i++) {
if (permissions[i].name === permission) {
return false;
}
}
return true; // 现在确保有一个返回值。
}
英文:
It is because you are not returning. If both conditions are not met.
Change
const permissionCheck = (permission) =>
{
var i;
for (i = 0; i < permissions.length; i++)
{
if (permissions[i].name === permission)
{
return false;
} else if (permissions[i].name !== permission) return true;
}
// 👈 There is no default return, so you are not getting any returned value
}
to
const permissionCheck = (permission) =>
{
var i;
for (i = 0; i < permissions.length; i++)
{
if (permissions[i].name === permission)
return false;
}
return true; // 👈 so now one return is assured.
}
答案2
得分: 0
尝试遍历一个无法工作的对象
将对象权限更改为数组
const [permissions, setPermissions] = useState([]);
并修改您的函数如下:
const permissionCheck = (permission) => {
var i;
for (i = 0; i < permissions.length; i++) {
if (permissions[i].name === permission) {
return false;
}
}
return true;
}
英文:
You try to iterate through an object which does not work
Change permissions from object
const [permissions, setPermissions] = useState({});
To array:
const [permissions, setPermissions] = useState([]);
And amend your function as follows:
const permissionCheck = (permission) =>
{
var i;
for (i = 0; i < permissions.length; i++)
{
if (permissions[i].name === permission)
{
return false;
}
}
return true;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论