【问题标题】:ReactJS - app functions in different filesReactJS - 不同文件中的应用程序功能
【发布时间】:2018-08-10 19:55:27
【问题描述】:

我正在尝试制作基于 React 的网页游戏。我有一个 App 组件,它几乎包含所有非 UX 状态。为了避免代码重复,我还将大多数函数保存在其中,并将其作为 prop 传递给子组件。

但现在我开始被不同的功能弄得一团糟,所有这些都在应用程序正文中。有什么简单的方法可以满足不同文件中的结构吗?我应该已经研究状态管理库了吗?

目前的东西看起来像:

    class App extends Component {
  constructor(props) {
    super(props);
    this.state = gameInitialize();
    this.modifyState = this.modifyState.bind(this);
    this.moveUnit = this.moveUnit.bind(this);
    this.progressMission = this.progressMission.bind(this);
    this.timeJump = this.timeJump.bind(this);
    this.competenceAfterTimeJump = this.competenceAfterTimeJump.bind(this);
    this.save = this.save.bind(this);
    this.load = this.load.bind(this);
  }
  componentDidMount() {
    this.timerID = setInterval(this.modifyState, this.state.interval);
    window.addEventListener('beforeunload', this.save);
    this.load();
  }
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
  save() {
    localStorage.setItem("gameSave", toJson(this.state));
  }
  load() {
    let state = 0;
    try {
      state = fromJson(localStorage.getItem("gameSave"));
    } catch (error) {
      console.log(error);
      return 0;
    }
    state.units.map(unit => {
      delete unit.__parent;
      delete unit.attributes.__parent
      return 0;
    });
    state.missions.map(mission => delete mission.__parent);
    this.setState(state);
  }
  modifyState() {
    this.setState(this.state.units.map(this.progressMission));
    this.setState(this.state);
  }
  progressMission(unit) {
    const mission = unit.currentMission;
    let increment = unit.attributes[mission.type].total() - mission.complexity;
    if (increment < 0) increment = 0;
    mission.progress += increment * this.state.interval / 1000 * unit.competence / 10;
    if (mission.progress >= mission.difficulty) {
      mission.progress = 0;
      this.state.experience.get(mission.reward);
      mission.completions += 1;
    }
  }
  moveUnit(unit, mission) {
    unit.currentMission = mission;
    this.setState(this.state);
  }
  timeJump() {
    const game = this.state;
    while (game.units.length > 2) {
      game.units.pop();
    };
    game.units.map(function (unit) {
      Object.keys(unit.attributes).map((key) => { unit.attributes[key] = newAttribute() });
      unit.currentMission = game.missions[0];
    });
    game.missions.map((mission) => {mission.progress = 0});
    game.units[0].competence = this.competenceAfterTimeJump();
    game.experience.current = 0;
    this.setState(game);
  }
  competenceAfterTimeJump() {
    return (10 + Math.sqrt(this.state.experience.total) / 10);
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="title">Time-traveling Hero: eventually I'll save the world, or maybe not if I don't feel it</h1>
        </header>
        <SaveLoad game={this} />
        <Prestige game={this} />
        <MissionWrapper>
          <MissionList missions={this.state.missions} game={this} />
        </MissionWrapper>
        <UnitWrapper>
          <ExpWrapper>
            <div>
              Available Experience: {this.state.experience.current.toFixed(1)}
            </div>
            <div>
              Total Experience: {this.state.experience.total.toFixed(1)}
            </div>
          </ExpWrapper>
          <UnitList units={this.state.units} game={this} />
        </UnitWrapper>
      </div>
    );
  }
}

function gameInitialize() {
  let game = { units: [], missions: [], currentUnit: undefined };

  game.interval = 10;

  game.missions = generateMissions(50);

  game.experience = {
    current: 0, total: 0,
    get: function (amount) { this.current += amount; this.total += amount },
    spend: function (amount) {
      if (this.current >= amount) {
        this.current -= amount;
        return true;
      }
      else return false;
    }
  };

  game.units.push({ name: "Hero", attributes: newAttributes(), competence: 10, currentMission: game.missions[0] });
  game.units.push({ name: "Childhood Friend", attributes: newAttributes(), competence: 15, currentMission: game.missions[0] });

  game.currentUnit = game.units[0];

  game.missionsWithUnits = function () {
    this.missions.map()
  }
  return game;
}

我应该如何进行?

【问题讨论】:

    标签: reactjs.net


    【解决方案1】:

    是的,组织 JS 代码非常容易!使用模块。以下是操作方法。

    1. 从文件中导出函数

    adders.js:

    export function addTwo (number) {
      return number + 2
    }
    
    1. 然后使用它:

    这可能在一个组件文件中:

    import { addTwo } from './path/to/adders.js'
    console.log(addTwo(5)) // logs 7
    

    你可以很好地组织很多事情。如果您有一组相关功能,请使用这样的模块。这是文件结构:

    mathStuff/
      adders.js
      index.js
    

    您的所有相关文件都在同一个文件夹中,并且您的函数从上面的单个文件中导出。然后像这样设置索引:

    index.js:

    import * as adders from './adders.js'
    // Set up your object however you want. 
    const MathStuff = {
      ...adders
    }
    export default MathStuff
    

    然后在任何组件中你都可以这样做:

    import MathStuff from './path/to/mathStuff'
    
    MathStuff.addTwo(7) // 9
    

    为了更有条理,您可以将索引设置为具有如下功能:

    index.js:

    import * as adders from './adders.js'
    import * as dividers from './dividers.js' // another math file with division functions or something
    
    // Set up your object however you want. 
    const MathStuff = {
      adders,
      dividers
    }
    export default MathStuff
    

    并像这样使用它:

    import MathStuff from './path/to/mathStuff' // points to directory, NOT individual file
    
    MathStuff.adders.addTwo(7) // 9
    

    我肯定会建议像这样组织代码。这改进的一件事是可测试性 - 测试纯函数非常容易,没有副作用。

    我喜欢将我的数据库代码放在一个模块中,然后将其导入到任何地方以访问我的所有数据库功能。

    我喜欢将我所有的业务逻辑按类别放在不同的模块中 - 例如GameLogic 或类似的东西。

    这也将帮助您编写更多功能代码。目前,您在单个函数中有很多状态修改 - 如果不将单个函数绑定到您的 react 组件的 this 上下文,您将无法在模块中执行此操作。相反,我建议将所有必要的参数传递给函数并让它返回一个值。这将业务逻辑移开,从而更容易管理状态。

    例如,您的progressMission 函数访问this.state.interval。您可以将interval 传递给函数本身。

    我注意到的一件事是,您的代码彼此之间有很多依赖关系——函数通常必须访问自身之外的许多东西,而不是自包含的。尝试重构为模块化系统可能会对您有很大帮助,其中函数更加纯粹 - 仅访问传递给它们的内容,并返回被使用的值。使用像上面这样的实际模块肯定有助于做到这一点——我做的越多,我的代码就越好。它可以帮助您更好地推理您的代码。此外,一旦/如果您开始实施测试,您会发现代码的所有复杂性使得测试变得困难 - 有很多副作用。

    最后,redux 和外部状态管理可能对您的情况没有多大帮助,但它们可能会。 Redux 可以帮助您实现更容易推理的状态,但它不会帮助您更好地组织代码本身。希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 2014-11-13
      相关资源
      最近更新 更多