简体   繁体   中英

Is it possible to use objects declared in useeffect hook?

I want to use object declared in useEffect hook, like

function App(){
  useEffect(() => {
    let myObject = .....
  }
  
  myObject.myFunction()
}

but IDE gives me an error that myObject is not defined...

I assume that it is not a good way to lead re-rendering objects declared in useEffect hook, but anyway, is there any way to use objects declared in useEffect hook?

I don't think so, because it's in different scope.

it would be ok to use state instead, because when useEffect call and object change, you wont get new value in object

like this:

function App(){
  const [myObject,setMyObject] = useState()
  useEffect(() => {
    setMyObject(...)
  },[])

  myObject?.myFunction()
}

First your code is wrong. It's not useeffect it's useEffect , so:

useeffect(() => {
  let myObject = .....
}

should be:

useEffect(() => {
  let myObject = .....
}

Second you would use useState in this scenario:

const [ myObject, setMyObject ] = useState()

  useEffect(() => {
    setMyObject(...)
  }, [])

  myObject?.myFunction()

Third make sure you're importing them correctly with something like:

import React, { useState, useEffect } from 'react'

function So75221887() {
  const [ myObject, setMyObject ] = useState()

  useEffect(() => {
    setMyObject(...)
  }, [])

  myObject?.myFunction()
}

export default So75221887

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM