【问题标题】:Pass variable update from static js File nextJs从静态 js 文件 nextJs 传递变量更新
【发布时间】:2022-08-20 20:47:16
【问题描述】:

我试图在我的组件中进行条件渲染,但我什至无法显示变量的值。

我在一个文件中有我在 index.js 中导出的所有函数

import FunctionServices from \"../services/functionServices\"

export default function Connect() {

 //const [accountId, setAccountId] = useState()

//let accountId = FunctionServices.accountId

//useEffect(() => {
//    setAccountId(FunctionServices.accountId)
//})

return (
<span>{FunctionServices.accountID}<span/>
<button onClick = {()=> FunctionServices.initconnect}> </button>
)

}

在我拥有所有功能的 functionServices 中:

let accountId;

async function initconnect() {

    //Account Id

    connect.pairingEvent.once(
        pairingData => {
            pairingData.accountIds.forEach(id => {
                accountId = id;
                console.log(`The account id is ${accountId}`)
            })
        }
    )
}
export default {accountId, initconnect}


我的 functionServices 文件,我可以显示 accountId,并对其进行控制台,但我怎样才能让它显示在我的 index.js 中。当它改变时。

我尝试使用上下文 api,但卡住了,因为我不知道如何将函数包装在提供程序中,因为它不是组件(functionServices)

感谢您的帮助和解释

    标签: javascript reactjs next.js


    【解决方案1】:

    把你的 index.js 写成

    import FunctionServices from "../services/functionServices"
    
    export default function Connect() {
      const [accountId, setAccountId] = useState(null)
    
      useEffect(() => {
          FunctionServices.initconnect(setAccountId)
      }, [])
    
      return (
        <span>{accountId}<span/>
      )
    
    }

    并且 initConnect 功能为

    async function initconnect(callback) {
    
        //Account Id
    
        connect.pairingEvent.once(
            pairingData => {
                pairingData.accountIds.forEach(id => {
                    accountId = id;
                    callback(id);
                    console.log(`The account id is ${accountId}`)
                })
            }
        )
    }

    【讨论】:

    • 我有错误回调不是函数
    • 我尝试在函数之外执行它,就像 const log = (callback) =&gt; { console.log(accountId) callback(accountId); } 在 initconnect 之后调用此函数时一样。但是我需要将它加载到 initconnect 中,当我这样做时它说它不是一个函数
    • @IlyesMakria 如果可能的话,你能给我源代码的链接吗
    【解决方案2】:

    我只需要将 export 放在每个函数的前面,而不是将它们全部放在 export default {...}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多