繁体   English   中英

在 React 中的组件之间共享变量数据

[英]Sharing varible data between components in React

我在 React 和 Node.js 中制作了一个触摸打字游戏,我想让 TypeScript 页面中的函数组件更新一个全局共享的 EXP 变量,以便玩家可以浏览应用程序页面并保留他们获得的 XP。 一旦他们关闭应用程序,变量就可以重置,它只需要每个会话。 这里有一些 XP 里面type.tsx的代码,它是一个在App.js的路由中调用的函数组件

Type.tsx

...

if (currIndex + 1 === length) {
      xpM = xpM + 1;
      bonusCounter = bonusCounter + 1;
      err = err + errorChar;
      currXP = xp * correctChar;
      addXP = (currXP - (err * 2)) * xpM;
      xpPercent = Math.round((uXP/xpNeed) * 100);
      (gain as HTMLAudioElement).play();
      console.log(xpPercent);
      if (err > correctChar) {
        addXP = correctChar * 3;
      }
      tXP = tXP + addXP;
      uXP = tXP;
...

我希望 tXP、xpNeed 和级别变量可以从 Select Test 组件以及其他打字页面访问(有 6 种不同的测试,使用不同的文本数组来填充打字文本。)我读过 Redux 可以做到这一点但在调查之后,我似乎需要重新构建整个应用程序才能使用 Redux 工具。 有没有一种快速而肮脏的方法来实现这一目标? 该应用程序仅用作正在开发的大型 Unity 游戏的演示,因此它不必是超级优雅或复杂的解决方案。 谢谢!

由于不适合 SO 的自以为是的答案,这个问题很可能会被关闭。

但是...我建议您使用React Context在您的组件之间共享状态。 您可以创建可从相关组件访问的 EXP 变量并共享更新。

如果您需要保持服务器同步,您可以在上面的 Context Provider 中更新本地状态时发布 EXP 增量,或者如果您需要实时通信并且游戏非常健谈,则使用socket.io

为全局变量及其方法创建一个类:

export default class GlobalVariables {
static createVariables() {
    //set here variables you want to be global
    this.tXP = 0;
}

static getXP() {//method to get XP
    return this.tXP;
}

static addXP(value) {//method to add XP
    this.tXP += value;
}

//create others methods you want for your variables
}

在您的启动组件中导入类并调用 createVariables(在应用程序启动时调用):

import GlobalVariables from './Global'
...
GlobalVariables.createVariables()
...

在您的其他组件中导入该类并使用其他方法:

import GlobalVariables from './Global'
...
GlobalVariables.addXP(5);
console.log(GlobalVariables.getXP())
...

暂无
暂无

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

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