最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I render a react component only after a state is set? - Stack Overflow

programmeradmin0浏览0评论

My app fetches some data from a server using useEffect and passes it as a prop to a child ponent. I would like to pause the rendering of the child ponent until the data is pletely fetched and loaded into a state. How can I achieve this?

My code(simplified):

const App = () => {
  const [data, setData] = useState(undefined)
  
  useEffect(async () => {
    const fetchedData = await getDataFromServer()
    setData(fetchedData)
  }, [])

  return (
    <div>
      <ChildComponent data={data} /> // How to pause rendering until data != undefined?
    </div>
  )
}

My app fetches some data from a server using useEffect and passes it as a prop to a child ponent. I would like to pause the rendering of the child ponent until the data is pletely fetched and loaded into a state. How can I achieve this?

My code(simplified):

const App = () => {
  const [data, setData] = useState(undefined)
  
  useEffect(async () => {
    const fetchedData = await getDataFromServer()
    setData(fetchedData)
  }, [])

  return (
    <div>
      <ChildComponent data={data} /> // How to pause rendering until data != undefined?
    </div>
  )
}
Share Improve this question asked Aug 19, 2022 at 17:40 Daniel JungDaniel Jung 1031 silver badge6 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

You can achieve this by using a ternary operator, since undefined is a falsy value the condition will return false and it will show Loading... until the data is fetched and after it is done fetching the condition will bee true since data is no longer undefined i.e. falsy that's how the data will be passed to the child ponent only after it is fetched.

const App = () => {
  const [data, setData] = useState(undefined)
  
  useEffect(async () => {
    const fetchedData = await getDataFromServer()
    setData(fetchedData)
  }, [])

  return (
    <div>
      {data ? <ChildComponent data={data} /> : <p>Loading...</p>}
    </div>
  )
}

More on falsy values here

More on ternary operator in Javascript here

Correct Way is first you check

state is not equal to initialstate

const [data,setData] = useState('initial state')

//ponent code 
 <>
   {data != 'initial state' && (data.length>0 ? data.map((dat)=>{} : <>no data</> ))                         }
 </>
发布评论

评论列表(0)

  1. 暂无评论