【问题标题】:Is there any way to change state inside render in React js?有没有办法在 React js 中改变渲染内部的状态?
【发布时间】:2020-03-29 01:45:12
【问题描述】:

所以我正在开发一个骰子应用程序,其中我有一个类组件,用于使用向上和向下按钮设置骰子的数量和每个骰子的边数。我的问题是,每次我按下向上或向下按钮来设置边数或骰子数时,都会创建一个随机数数组并显示在屏幕上。但是,我希望仅在单击滚动按钮时显示该值。

那么有没有一种方法可以在我在渲染中创建数组后将 displayDice 的状态更改为 false,这样只有当我再次单击滚动按钮时它才会变为 true

【问题讨论】:

    标签: javascript reactjs babeljs


    【解决方案1】:

    您可以将逻辑移至componentDidMount。渲染只是渲染 UI。没有业务逻辑。它将处理事件并委托给状态。

    将生成随机移动到父组件,将方法rollChange从父组件传递给子组件。

    //骰子组件

    class SideAndDice extends React.Component {
      constructor(props) {
        super(props);
        this.state = { sides: 6, dice: 1, randoms: this.generateRandom() };
      }
      increaseDice() {
        this.setState({ dice: this.state.dice + 1 });
      }
      decreaseDice() {
        if (this.state.dice > 1) {
          this.setState({ dice: this.state.dice - 1 });
        }
      }
      increaseSides() {
        this.setState({ sides: this.state.sides + 1 });
      }
      decreaseSides() {
        if (this.state.sides > 2) {
          this.setState({ sides: this.state.sides - 1 });
        }
      }
      generateRandom() {
        let randoms = [];
        for (var i = 0; i < this.state.dice; i++) {
          var randomValue = Math.floor(Math.random() * this.state.sides + 1);
          randoms.push(randomValue);
        }
        return randoms;
      }
      onRollDice() {
        this.setState({ randoms: this.generateRandom() });
      }
      render() {
        return (
          <div>
            <h1>Number of Sides</h1>
            <h2>{this.state.sides}</h2>
            <button onClick={this.increaseSides.bind(this)}>Up</button>
            <button onClick={this.decreaseSides.bind(this)}>Down</button>
            <h1>Number of Dice</h1>
            <h2>{this.state.dice}</h2>
            <button onClick={this.increaseDice.bind(this)}>Up</button>
            <button onClick={this.decreaseDice.bind(this)}>Down</button>
            <CreateScores
              randoms={this.state.randoms}
              rollChange={this.rollChange.bind(this)}
            />
          </div>
        );
      }
    }
    class CreateScores extends React.Component {
      render() {
        return (
          <div>
            <button onClick={this.props.onRollDice.bind(this)}>Roll</button>
            <br />
            <br />
            {this.props.randoms.map(random => (
              <Dice key={i} diceNumber={randomValue} />
            ))}
          </div>
        );
      }
    }
    

    【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2019-09-23
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2020-05-20
    • 2019-01-25
    • 2020-11-05
    • 2015-12-21
    相关资源
    最近更新 更多