Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 修复useEffect挂钩中的过时状态_Javascript_Reactjs_React Hooks - Fatal编程技术网

Javascript 修复useEffect挂钩中的过时状态

Javascript 修复useEffect挂钩中的过时状态,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我已经修复了当react首次初始化state对象时,使用基于闭包的“stale”/old状态值进行useffect回调的问题。以前,当装载后执行useffect回调时,它只能访问第一个状态值,即null。我通过添加state对象,isSignedIn作为useffect钩子的第二个参数来解决这个问题。现在,useffect在调用changeSignInStatus时重新运行,这意味着在第一次渲染后,第一次运行useffect回调,但随后使用更新的状态值再次运行。因此,我的应用程序可以访问新的状态

我已经修复了当react首次初始化state对象时,使用基于闭包的“stale”/old状态值进行useffect回调的问题。以前,当装载后执行
useffect
回调时,它只能访问第一个状态值,即
null
。我通过添加state对象,
isSignedIn
作为
useffect
钩子的第二个参数来解决这个问题。现在,
useffect
在调用
changeSignInStatus
时重新运行,这意味着在第一次渲染后,第一次运行
useffect
回调,但随后使用更新的状态值再次运行。因此,我的应用程序可以访问新的状态值

但是,我希望在状态对象更新时避免不断地重新运行
useffect
回调,因为我不想每次都重新加载googleauth库

有人知道我如何解决
useffect
钩子中的过时状态问题,而不必将我的state对象作为第二个
useffect
参数吗

function GoogleAuth(){

    const [isSignedIn,changeSignInStatus] = useState(null);

    var auth

    useEffect(()=>{
        //load client:auth2 library and define a callback
        window.gapi.load('client:auth2',()=>{
            window.gapi.client.init({
                clientId:"*****************************",
                scope:"email"
            }).then(()=>{
                auth = window.gapi.auth2.getAuthInstance();
                changeSignInStatus(auth.isSignedIn.get());
                auth.isSignedIn.listen(onAuthChange);
            });
        });


    },[isSignedIn]);


在这里添加它,因为建议很大

第一个问题:在依赖项数组中不使用isSignedIn时,哪个值已过时

第二,根据您的代码,我们可以进行如下修复,以避免重复加载库:

function GoogleAuth() {
  const [isSignedIn, changeSignInStatus] = useState(null);

  var auth;

  useEffect(() => {
    //load client:auth2 library and define a callback
    if (!isSignedIn) {
      window.gapi.load("client:auth2", () => {
        window.gapi.client
          .init({
            clientId: "*****************************",
            scope: "email",
          })
          .then(() => {
            auth = window.gapi.auth2.getAuthInstance();
            changeSignInStatus(auth.isSignedIn.get());
            auth.isSignedIn.listen(onAuthChange);
          });
      });
    }
  }, [isSignedIn]);
}

请告诉我您的想法?

在Dependency数组中未使用isSignedIn的情况下获得了哪些过时数据?
auth
每次重新渲染都将重新初始化为
undefined