javascript - 如何遍历 react 状态变量数组并确定它是否有一个真值

标签 javascript reactjs ecmascript-6

我有一个如下所示的状态变量

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/

相关文章:

javascript - 带有喜欢和评论选项的评论框代码

javascript - 从 Backbone.js 模型中完全删除属性

javascript - React-Native Android 操作错误 : 'undefined is not an object (evaluating ' action. 类型')'

javascript - 在 ssr 应用程序中单击时,react-router-dom <Link/> 会清除 {history,match,location} 属性

javascript - React - 如何在另一个组件中显示来自图像 onClick 事件的组件?

javascript - 从数组中获取具有最高优先级的字符串的最有效方法

javascript - Electronjs 检测窗口变化

javascript - 首先按特定值对 meteor 集合进行排序

javascript - 从 jQuery onChange 使用 Vue 更新数据值

javascript - JS 中的连接函数