javascript - React setstate 采用以前的值

标签 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;

最佳答案

setState 是异步的,因此如果您尝试在调用 setState 后立即使用它,this.state 仍将包含之前的值。

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

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);
  });
}

关于javascript - React setstate 采用以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53136385/

相关文章:

javascript - 安装react-router-dom时遇到错误

javascript - 使用 onClick 事件渲染 JSX Switch Case

reactjs - react-redux connect 不会重新渲染组件,但 props 会更新

javascript - 在 IE8 中转换对象(仅旋转),类似于使用 CSS3 transform(rotate), transform-origin

javascript - 输入字段在移动 View 中不可编辑

javascript - 如何使用行下方的 JSON 和 Javascript 填充表格

javascript - Flux:顶级 View 不应为 "dump"(不从存储中获取数据)

javascript - 从父到子 react 使用引用

javascript - 在隔离作用域指令中,在作用域上定义变量和在 Controller 上定义变量之间有什么区别吗?

javascript - 字符串终止问题