简体   繁体   English

如何在反应中导出setTimeout中定义的const?

[英]How to export const defined inside setTimeout in react?

Beginner here, I have a setTimeout configured something like this that parses json from session storage初学者在这里,我有一个类似这样的 setTimeout 配置,它从 session 存储中解析 json

  setTimeout(() => {
    const blog = JSON.parse(sessionStorage.blogs);
    console.log(blog);
  }, 1000)

all I want to do is use the blog const outside the timeout which would make things easier,我想做的就是在超时之外使用博客常量,这会使事情变得更容易,

setTimeout(() => {
    const blog = JSON.parse(sessionStorage.blogs);
  }, 1000)    
console.log(blog); <------ this does not work

I get the Undefined error我收到未定义的错误

'blog' is not defined  no-undef

If you need it outside, you'll need如果你在外面需要它,你需要

  • to use state so you can set the state inside the timeout callback使用 state 所以你可以在超时回调中设置 state
  • to log it only when it gets initialized, and not on every render, use useEffect with it in the dependency array要仅在初始化时记录它,而不是在每次渲染时记录它,请在依赖数组中使用useEffect
const [blog, setBlog] = useState();
useEffect(() => {
  setTimeout(() => {
    setBlog(JSON.parse(sessionStorage.blogs));
  }, 1000);
}, []); // run only once, on mount
useEffect(() => {
  if (blog) { // only log once it exists
    console.log(blog);
  }
}, [blog]); // run only when the state changes

I think you can use Promise to help you to fix this problem.我认为您可以使用Promise来帮助您解决此问题。

 const [blog, setBlog] = useState() new Promise((resolve) => { setTimeout(() => { const sessionBlog = JSON.parse(sessionStorage.blogs); resolve(sessionBlog); }, 1000) }).then((res) => { console.log(res); setBlog(res); }) useEffect(() => { console.log('blog has changed, you can do whatever you want here') }, [blog])

That's because setTimeout is async, your console.log will run first before the setTimeout (even if it is 0 seconds)..那是因为 setTimeout 是异步的,您的 console.log 将在 setTimeout 之前首先运行(即使它是 0 秒)..

How about this这个怎么样

let blog;
setTimeout(() => {
    blog = JSON.parse(sessionStorage.blogs);
  }, 1000)    
console.log(blog);

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

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