我有一个如下所示的状态变量
const Home = ({ t, i18n, history }) => {
const [otherStudiosAvailable, setOtherStudiosAvailable] = useState([]);
const studios = ["de", "fr", "pl", "en", "nl", "ru"];
const otherStudios = studios.filter(item => {
return item !== i18n.language;
});
useEffect(() => {
let others = [];
for (const studio of otherStudios) {
checkForAvailableAgent(
`sales_${studio}`,
"Linktostudio",
"serviceID"
)
.then(res => {
others[studio] = res;
setOtherStudiosAvailable(others);
})
.catch(error => {
console.log("an error happened.");
});
}
}, []);
}
{otherStudiosAvailable.indexOf(true) ? (
<Button
variant="success"
onClick={e => callBtnClick("flag")}
>
Other studios available
</Button>
) : ("")
}
我需要在基于 otherStudiosAvailable 的 JSX 中进行条件检查(如果它至少有一个真实值)
如有任何帮助,我们将不胜感激。
最佳答案
实际上,如果数组中不存在 true,则 indeOf 会返回 -1 但 -1 的真值是 true,因此您需要显式检查它是否不等于 -1(表示元素存在) Object.values(otherStudiosAvailable) 返回此对象中存在的值的数组
{Object.values(otherStudiosAvailable).indexOf(true)!==-1 ? (
<Button
variant="success"
onClick={e => callBtnClick("flag")}
>
Other studios available
</Button>
) : ("")
}
关于javascript - 如何遍历 react 状态变量数组并确定它是否有一个真值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58336853/