【问题标题】:Why my radio button's checked property remains unchanged even though state changes (React)为什么即使状态发生变化,我的单选按钮的选中属性仍然保持不变(反应)
【发布时间】:2021-02-12 01:07:28
【问题描述】:

我是 React 新手,无法在与我的问题相关的其他帖子中找到解决方案。

我正在构建一个简单的页面,该页面显示一组四个无线电输入以选择要注册的用户类型。问题在于我相信的状态的处理。

import React, { Component/*, useEffect*/ } from 'react'


export default class CreateUser extends Component {
  
  constructor(props) {
    super(props);
    this.state = {
      clasificacion: "",
      rol: ""
    };
  }
  setClasificacionRadio = (e) => {
    console.log(e.currentTarget);
    this.setState({clasificacion: e.currentTarget.value}, 
      ()=>{
        console.log("clasificacion: "+this.state.clasificacion);
      }
    );    
  }
  setRolRadio = (e) => {
    console.log(e.currentTarget);
    this.setState({rol: e.currentTarget.value}, 
      ()=>{
        console.log("Rol: "+this.state.rol);
      }
    );
  }
  render() {
    return (
      <div className="container">
        <div className="row mt-3">
          <div className="col-12 col-md-12">
            <h3 className="text-center font-weight-bold">Registro de Usuarios</h3>
          </div>           
        </div>
        <div className="row mt-5">
          <div className="col-12 col-md-12">
            <h4 className="text-center font-weight-bold">Seleccione la Clasificación del Usuario</h4>
          </div>           
        </div>
        <div className="row mt-2">
          <div className="col-12 col-md-6 offset-md-3">
            <div className="input-append">
              <div className="btn-group pull-left" data-toggle="buttons">
                <label className="">Empleado</label>
                  <input type="radio" name="clasif" className='form-check' value="btn1"
                    onChange={this.setClasificacionRadio} 
                    checked={this.state.clasificacion === "btn1"}
                    style={{marginTop: 15, marginLeft: 5, marginRight: 20}}
                  />
                <label className="">Institución</label>
                  <input type="radio" name="clasif" className='form-check' value="btn2"
                    onChange={this.setClasificacionRadio} 
                    checked={this.state.clasificacion === "btn2"}
                    style={{marginTop: 15, marginLeft: 5, marginRight: 20}}
                  />

                <label className="">Socio</label>
                  <input type="radio" name="clasif" className='form-check' value="btn3"
                    onChange={this.setClasificacionRadio} 
                    checked={this.state.clasificacion === "btn3"}
                    style={{marginTop: 15, marginLeft: 5, marginRight: 20}}
                  />

                <label className="">Obra Social</label>
                  <input type="radio" name="clasif" className='form-check' value="btn4"
                    onChange={this.setClasificacionRadio} 
                    checked={this.state.clasificacion === "btn4"}
                    style={{marginTop: 15, marginLeft: 5, marginRight: 20}}
                  />
              
              </div>
            </div>
          </div>           
        </div>
        <div className="row mt-5">
          <div className="col-12 col-md-12">
            <h4 className="text-center font-weight-bold">Seleccione el Rol del Usuario a Crear</h4>
          </div>           
        </div>
        <div className="row mt-2">
          <div className="col-12 col-md-6 offset-md-3">
            <div className="input-append">
              <div className="btn-group pull-left" data-toggle="buttons">
                <label className="">Administrador</label>
                  <input type="radio" name="rol" className='form-check' value="ROL1"
                    onChange={this.setRolRadio} 
                    checked={this.state.rol === "ROL1"}
                    style={{marginTop: 15, marginLeft: 5, marginRight: 20}}
                  />
                <label className="">Facturador</label>
                  <input type="radio" name="rol" className='form-check' value="ROL2"
                    onChange={this.setRolRadio} 
                    checked={this.state.rol === "ROL2"}
                    style={{marginTop: 15, marginLeft: 5, marginRight: 20}}
                  />

                <label className="">Usuario de Carga</label>
                  <input type="radio" name="rol" className='form-check' value="ROL3"
                    onChange={this.setRolRadio} 
                    checked={this.state.rol === "ROL3"}
                    style={{marginTop: 15, marginLeft: 5, marginRight: 20}}
                  />
              
              </div>
            </div>
          </div>           
        </div>
        <div className="row mt-5">
          <div className="col-12 col-md-4 offset-md-4">
            <button id="" className="btn btn-outline-dark btn-block">
              Continuar
            </button>
          </div>
        </div>
      </div>
    )
  }
}

即使状态发生变化,单选按钮的选中属性保持不变,因此单选按钮永远不会被选中。

编辑

更新为将开关放置在 setState 回调中,以便按照 @Dhruvi Makvana

的建议正确显示状态更改

问题仍然存在,单选按钮保持未选中状态,但单击它们会在控制台中显示状态更改。

编辑 2

我添加了第二行的 4 个单选按钮,其中包含它自己的比较、状态和功能。我意识到只有当我单击第二行中的单选按钮时才会更新第一行的单选按钮,反之亦然,还意识到检查的属性没有根据来自 setState 的异步调用进行更新。上面的代码已更新以显示这些更改。

此时我在想我或许应该更改这篇文章的标题?,建议?

编辑 3

我像 @Vimal Patel 那样在沙箱中运行更新后的代码,它运行良好,我不知道如何调试这个问题。 沙盒:https://codesandbox.io/s/stupefied-jennings-sxbfn

【问题讨论】:

  • 错字。 onChange={this.setClasificacionRadio}。您缺少(),应该是onChange={this.setClasificacionRadio()}
  • 嘿,语法是正确的。 SetState 不会立即更新。 stackoverflow.com/questions/41446560/…
  • 我在这里创建了一个沙箱。工作正常。请查看codesandbox.io/s/eloquent-wood-fdf8v?file=/src/index.js
  • 我可以在这个代码库中看到同样的问题。
  • @VimalPatel 是的,我可以看到它在那里工作正常,您是否更改了代码中的任何内容?我的还是不行。

标签: javascript reactjs radio-button


【解决方案1】:

this.setState() 是异步的,这意味着它不保证下一行中的更新状态。尝试在另一个函数中移动开关盒或将其放入 setState 回调中。

【讨论】:

  • 是的,我通过将它放在 setState 的回调中来更正了开关,它现在显示状态更新,问题仍然存在,我可以在控制台中看到状态发生变化,但是单选按钮不会更改其选中属性。
  • 您可以尝试将值更改为“btn1”、“btn2”.. 并分别进行比较。
  • 所以最初在将收音机的值更改为“btn-1”、“btn2”之后..按照建议,没有任何改变,但后来我尝试了一些东西,我添加了第二行 4 个单选按钮,它是自己的比较,状态和功能。我意识到第一行并没有自己更改选中的属性,我需要单击第二行中的一些单选,以便更新选中的属性。我将使用更改更新我的代码。这不应该这么难。
猜你喜欢
  • 2016-12-15
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 2011-08-02
  • 2016-02-26
  • 1970-01-01
相关资源
最近更新 更多