反应 setstate 取以前的值

Shi*_*ral 6 javascript reactjs

我编写了下面的 react 组件来处理我使用 react 制作的扫雷艇克隆的难度级别。

我使用单选按钮作为难度输入,并希望根据所做的选择设置组件的状态。

我的问题是每次更改选择时,状态都会更新为我之前的选择而不是当前选择的值。例如,在页面加载期间,所选难度为“简单”。当我将难度更改为“困难”时,状态仍然显示初始设置,即“简单”(我做了状态的控制台日志来验证这一点)。

请帮忙。

import React, {Component} from 'react';

class Difficulty extends Component{

  state = {
      height: 8,
      width: 8,
      mines: 10,
  };

  setDifficulty(event){
    let selectedDifficulty = event.target.value;
    if (selectedDifficulty === "Easy") {
        this.setState({
            height: 8,
            width: 8,
            mines: 10,
        });
    }
    if (selectedDifficulty === "Medium") {
        this.setState({
            height: 12,
            width: 12,
            mines: 20,
        });
    }
    if (selectedDifficulty === "Hard") {
        this.setState({
            height: 16,
            width: 16,
            mines: 40,
        });
    }
    this.props.updateDifficulty(this.state);
  }

  render(){
    return(
      <div className="game-difficulty">
        <div className="difficulty" onChange={this.setDifficulty.bind(this)}>
          <input type="radio" value="Easy" name="gender" defaultChecked="true" /> Easy
          <input type="radio" value="Medium" name="gender" /> Medium
          <input type="radio" value="Hard" name="gender" /> Hard
        </div>
      </div>
    );
  }
}

export default Difficulty;
Run Code Online (Sandbox Code Playgroud)

Tho*_*lle 5

setState是异步的,因此this.state如果您在调用setState.

您可以改为执行依赖于this.state作为第二个参数给出的函数的逻辑,该函数setState将在状态更新时运行。

setDifficulty(event) {
  let selectedDifficulty = event.target.value;
  let values;

  if (selectedDifficulty === "Easy") {
    values = {
      height: 8,
      width: 8,
      mines: 10
    };
  }
  if (selectedDifficulty === "Medium") {
    values = {
      height: 12,
      width: 12,
      mines: 20
    };
  }
  if (selectedDifficulty === "Hard") {
    values = {
      height: 16,
      width: 16,
      mines: 40
    };
  }

  this.setState(values, () => {
    this.props.updateDifficulty(this.state);
  });
}
Run Code Online (Sandbox Code Playgroud)