简体   繁体   English

使用 React Hooks 实现时间延迟

[英]Implementing time delay using React Hooks

I would like to know how to implement time delay in React functional component.我想知道如何在 React 功能组件中实现时间延迟。 Pseudocode is given below伪代码如下

const staring_function = () => {
  return(
    //renders components
  )
}
const main_function = () => {
  return(
    //renders components
  )
}

I would like to run starting_function for 3 seconds to render some texts on the screen on loading after which the main_function run to replace the contents of the starting_function.我想运行starting_function 3秒以在加载时在屏幕上呈现一些文本,然后main_function运行以替换starting_function的内容。 for example the page displaying a text "LOADING... " for few seconds and then displaying the contents.例如,页面显示文本“正在加载...”几秒钟,然后显示内容。

I have been working on this for some days yet still cant get around.我已经为此工作了几天,但仍然无法解决。 I know it has something to do with useEffect hook.我知道它与 useEffect 挂钩有关。 It would have been helpful if someone could help me out.如果有人可以帮助我,那将会很有帮助。 Thank you谢谢

You don't need useEffect hook.你不需要useEffect钩子。 Try following code:试试下面的代码:

const [ loading, setLoading ] = useState(true)

setTimeout(() => {
  console.log('now')
  setLoading(false)
}, 3000)

if (loading) {
  return (
    <div>LOADING...</div>
  )
}

return (
  <div>content</div>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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