如何解决Strict Mode重新渲染问题

huangapple go评论87阅读模式
英文:

How to solve Strict Mode Re-render issue

问题

我有一个React代码,它的工作方式如下:

const [screenStream, setScreenStream] = useState(null);

useEffect(() => {
  getPermissionsAndStreams();
}, []);

const getPermissionsAndStreams = () => {
  getDisplayStream()
    .then((_screenStream) => {
      // After permission given
      setScreenStream(_screenStream);
      // ...
    });
};

也就是说,当组件加载时,它会向用户请求权限,并将其保存到setStream变量中。

然而,当React的StrictMode开启时,这并不起作用。它似乎存在一个竞态条件,导致页面重新加载,将screenStream重置为null,之后才激活setScreenStream

是否有一种不会出现这个问题的不同代码模式?或者我们必须关闭严格模式(Strict Mode)?

英文:

I have react code that works like so:

  const [screenStream, setScreenStream] = useState(null);

  useEffect(() => {
    getPermissionsAndStreams();
  }, []);

  const getPermissionsAndStreams = () => {
    getDisplayStream()
      .then((_screenStream) => {
        // After permission given
        setScreenStream(_screenStream);
        ...
      });
  };

I.e. when the component loads, it requests permission from the user and saves that to the setStream variable.

However, this does not work when react's StrictMode is turned on. It seems to have a race condition where the page reloads, resetting screenStream to null, after setScreenStream has been activated.

Is there a different pattern of code that would avoid this problem? Or do we have to turn off strict mode?

答案1

得分: 1

这真的很奇怪,将值设置为另一个值后,该值会变回null,useState钩子仅在第一次执行时接收null,然后由setScreenStream管理,唯一将其设置为null的方法是故意设置它

有可能是服务出现了问题,或者还有另一个setScreenStream影响了您的开发

还要检查const getPermissionsAndStreams的位置,尝试将其放在useEffect之上,记住,对于const,提升不会按您期望的方式工作

英文:

It's really weird that the value came back to null after set it to another value, useState hook receive null only the first execution then it is managed by setScreenStream, the only way to go back to null is setting that intentionally

Could be that the service is failing by any chance or there is another setScreenStream affecting your development

Also check the position of const getPermissionsAndStreams try tu put it above the useEffect, remember that with const, hoisting is not working as you could expect

huangapple
  • 本文由 发表于 2023年6月15日 21:37:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定