【问题标题】:Does use useState inside useEffect doesn't works?在 useEffect 中使用 useState 是否不起作用?
【发布时间】:2021-12-04 10:21:45
【问题描述】:

我在 useEffect 中调用了这个函数。我得到的输出是 user idddd is null 616830f1491ef15dc0ba5a6a 。虽然 id 变量在 console.log 语句中给了我正确的值,但 userId 仍然为空。我不确定为什么会这样。

function Component() {
const [userId, setuserId]= useState(null);

useEffect(()=>{
   getUserId()
        .then((id)=>{
          setuserId(id);
          console.log("user idddd is", userId, id);
         
        })
},[])

  function getUserId() {
    let id = localStorage.getItem("userId");
    return new Promise((resolve, reject)=>{
      if(id){
        resolve(id);
      }
      reject();
    })
  }
.
.
.
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    即使您在 useEffect 中设置了状态,它也只会在组件的下一次渲染时更新。这就是为什么在你设置它之后立即 console.log() 时它为空的原因。

    【讨论】:

      【解决方案2】:

      你不能指望 javascript 执行setuserId 来更新值然后返回到console.log 你更新的用户ID

        setuserId(id);
        console.log("user idddd is", userId, id);
      

      setUserId 将在您的整个 .then() 完成后立即更新值

      【讨论】:

        猜你喜欢
        • 2021-09-06
        • 2023-01-17
        • 2022-01-06
        • 2020-08-14
        • 2020-10-21
        • 1970-01-01
        • 2020-10-20
        • 2021-07-18
        • 2021-10-16
        相关资源
        最近更新 更多