簡體   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