最新消息:20210917 已从crifan.com换到crifan.org

【已解决】ReactJS中如何保和传递存全局变量

ReactJS crifan 3292浏览 0评论

之前已经:

【已解决】ReactJS中如何实现公用的全局函数

但是现在需要的是:

在用iOS/Android的原生APP登录后,调用我的H5的ReactJS的页面,传递对应的用户信息

而此用户信息,会在其他的所有的页面中被用到。

甚至可能修改这个变量的值。

搜:

reactjs global variable

参考:

reactjs – How to declare a global variable in React? – Stack Overflow

如果用Context,那么其他非child的页面就访问不到了。

所以貌似可以去用window.xxx

【总结】

然后此处就是去用window.xxx去赋值

然后其他地方,去判断window.xxx是否为空,不为空,就可以使用了。

/src/container/app.js

  //Native(iOS/Android):loginCallback(String userInfoJsonStr);
  loginCallback(userInfoJsonStr){
    if (window.hasCallLoginCallback) {
      return;
    }
    window.hasCallLoginCallback = true;
    console.log(`loginCallback: userInfoJsonStr=${userInfoJsonStr}`);
    //alert(userInfoJsonStr);
    // let userInfoDict = Object(userInfoJsonStr);
    let userInfoDict = JSON.parse(userInfoJsonStr);
    console.log(userInfoDict);
    // alert(userInfoDict);
    console.log(typeof(userInfoDict)); //object
    console.log(userInfoDict.currentCowfarmId);
    console.log(userInfoDict.cowfarmList);
    console.log(typeof(userInfoDict.cowfarmList)); //object
    window.userInfoDict = userInfoDict;
    console.log(window.userInfoDict);
    // alert(JSON.stringify(window.userInfoDict));
  }

别处调用:

src/container/profile/index.js

  fetchUserInfo() {
    if (window.userInfoDict && window.userInfoDict.userId) {
      const url = `/person/person/basicInfo?userId=${window.userInfoDict.userId}`;
。。。
    }
  }

转载请注明:在路上 » 【已解决】ReactJS中如何保和传递存全局变量

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.186 seconds, using 23.38MB memory