【问题标题】:ReactJS - How to return a string from functional component?ReactJS - 如何从功能组件返回字符串?
【发布时间】:2021-08-27 12:15:22
【问题描述】:

在反应中,我将 @apollo/client 用于后端 API。在appollo.js 中,我正在尝试根据条件调用后端 API 链接。

现在appollo.js 只包含函数,它不是组件。

我正在尝试为其添加 statsig 功能,const featureOn = useGate(<FEATURE_GATE_NAME>).value;

如何在appollo.js 中使用 statsig 变量?

我也尝试过创建单独的组件并像<AbcComponent /> 一样渲染,但它没有返回所需的值。

AbcComponent.js,

export const AbcComponent = () => {
  const featureOn = useGate('abc').value
  return featureOn ? 'Yes' : 'no'
}

在这种情况下,我如何从appollo.js 获得“是/否”?

【问题讨论】:

    标签: javascript reactjs next.js components client


    【解决方案1】:

    react 中的组件应该总是返回一个 JSX 。你需要的是一个自定义钩子。

    export const useCheckFeatureOn = () => {
        const featureOn = useGate('abc').value
        return featureOn ? 'Yes' : 'no'
      }
    

    在任何你想使用值的地方使用上面的钩子

    const isFeatureOn = useCheckFeatureOn();
    

    【讨论】:

    • 但是useCheckFeatureOn不能直接在appollo.js中调用,应该在组件里面吧。
    • @ShruthiR 在 apollo 客户端中使用钩子的一种方法是将 apollo.js 的内容移动到 App.js 并在那里进行 apollo 初始化。
    猜你喜欢
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多