重构组件ReactJS

问题描述 投票:1回答:2

我在React中还很陌生,我正在尝试制作一个简单的Clicker游戏。就目前而言,一切工作正常(我认为),但是我认为代码非常重复(我使用了很多setState)。有人可以告诉我如何使其更清洁并处理状态吗?我不要求您为我重构此代码,只是为如何做提供建议。感谢您的任何建议。

这是我的代码:

import React, { Component } from 'react';

class Enemy extends Component {
  constructor(props) {
    super(props);

    this.state = {
      hp: 10,
      nextHp: 12,
      clickDamage: 1,
      gold: 0,
      dps: 0.1,
      num: 1,
      tapCount: 0,
      itemCount: 0,
      tapCost: 10,
      itemCost: 50
    };

    this.handleClick = this.handleClick.bind(this);
    this.buyTap = this.buyTap.bind(this);
    this.buyItem = this.buyItem.bind(this);
  }

  componentDidMount() {
    const interval = setInterval(() => {
      this.setState({ hp: this.state.hp -= this.state.dps });
      if(this.state.hp <= 0) {
        this.setState({ hp: this.state.hp = this.state.nextHp });
        this.setState({ nextHp: Math.floor(this.state.nextHp * 1.2) })
        this.setState({ gold: this.state.gold + 10});
        this.setState({ num: Math.floor(Math.random() * 4 + 1)});
      }
    }, 100);
  }

  handleClick() {
    this.setState({ hp: this.state.hp - this.state.clickDamage });

    if(this.state.hp <= 0) {
      this.setState({ hp: this.state.hp = this.state.nextHp });
      this.setState({ nextHp: Math.floor(this.state.nextHp * 1.2) })
      this.setState({ gold: this.state.gold + 10});
      this.setState({ num: Math.floor(Math.random() * 4 + 1)});
    }
  }

  buyTap() {
    if (this.state.gold >= this.state.tapCost) {
      this.setState({ gold: this.state.gold -= this.state.tapCost });
      this.setState({ tapCount: this.state.tapCount += 1 });
      this.setState({ clickDamage: this.state.clickDamage += 1 })
    }
  }

  buyItem() {
    if (this.state.gold >= this.state.itemCost) {
      this.setState({ gold: this.state.gold -= this.state.itemCost });
      this.setState({ itemCount: this.state.itemCount += 1 });
      this.setState({ dps: this.state.dps += 0.1 });
    }
  }

  render() {
    return (
      <div>
        <div className="container ui center aligned">
          <h1>Enemy hp: {Math.round(this.state.hp)}</h1>
          <h3>Gold: {this.state.gold}</h3>
          <h3>Click damage: {this.state.clickDamage}</h3>
          <h3>Damage per second: {Math.round(this.state.dps * 10)}</h3>
          <img
            alt=""
            className="dragon"
            src={require("../img/dragon" + this.state.num + ".jpg")}
            onClick={this.handleClick}
            draggable={false}
          />
        </div>
        <div className="ui container">
          <img
            onClick={this.buyTap}
            alt=""
            style={{ width: '50px' }}
            src={require("../img/tap.png")}
          />
          <p>Count: {this.state.tapCount}</p>
          <p>Cost: {this.state.tapCost}</p>
          <img
            onClick={this.buyItem}
            alt=""
            style={{ width: '50px' }}
            src={require("../img/rapier.png")}
          />
          <p>Count: {this.state.itemCount}</p>
          <p>Cost: {this.state.itemCost}</p>
        </div>
      </div>
    );
  }
}

export default Enemy;
javascript reactjs refactoring code-cleanup
2个回答
3
投票

没有太多要考虑的因素。但是我可以说,您所有的状态更新都可以合并。您可以一次更新多个状态值。

this.setState({ hp: this.state.hp = this.state.nextHp });
this.setState({ nextHp: Math.floor(this.state.nextHp * 1.2) })
this.setState({ gold: this.state.gold + 10});
this.setState({ num: Math.floor(Math.random() * 4 + 1)});

to

this.setState({
  hp: this.state.nextHp,
  nextHp: Math.floor(this.state.nextHp * 1.2),
  gold: this.state.gold + 10,
  num: Math.floor(Math.random() * 4 + 1)
});

旁注:状态突变,例如this.state.hp = this.state.nextHp是一种反作用模式,可能导致错误。

第二面说明:对于依赖于当前状态值的状态更新,最好使用功能状态更新,这样在渲染中触发多个更新的情况下,状态更新应正确排队并处理循环。

this.setState(prevState => ({
  hp: prevState.nextHp,
  nextHp: Math.floor(prevState.nextHp * 1.2),
  gold: prevState.gold + 10,
  num: Math.floor(Math.random() * 4 + 1)
}));

这里是我的codesandbox demo,它说明了为什么此功能更新can很重要。


0
投票

除了按照@Drew Reese的答案将setState组合为一个,还可以通过将方法定义为类中的箭头函数来避免绑定方法(即this.handleClick = this.handleClick.bind(this);):

  handleClick = () => {
    // ...
  }

  buyTap = () => {
    // ...
  }

  buyItem = () => {
    // ...
  }

这样,您还可以从中删除构造函数

  constructor(props) {
    super(props);

    this.state = {
      hp: 10,
      nextHp: 12,
      clickDamage: 1,
      gold: 0,
      dps: 0.1,
      num: 1,
      tapCount: 0,
      itemCount: 0,
      tapCost: 10,
      itemCost: 50
    };

    this.handleClick = this.handleClick.bind(this);
    this.buyTap = this.buyTap.bind(this);
    this.buyItem = this.buyItem.bind(this);
  }

// (State is defined without a constructor as an instance variable)
state = {
    hp: 10,
    nextHp: 12,
    clickDamage: 1,
    gold: 0,
    dps: 0.1,
    num: 1,
    tapCount: 0,
    itemCount: 0,
    tapCost: 10,
    itemCost: 50
};
© www.soinside.com 2019 - 2024. All rights reserved.