React复选框不更新

Gab*_*kel 5 javascript checkbox reactjs redux react-redux

我想每次将复选框切换为true时更新一个数组。使用当前代码,如果我单击一个复选框,则会记录为错误。即使我刚刚更新了状态。setState是否需要一些时间,例如API调用?这对我来说没有意义。

import React, {Component} from 'react';

class Person extends Component {

  constructor(props) {
    super(props);

    this.state = {
      boxIsChecked: false
    };

    this.checkboxToggle = this.checkboxToggle.bind(this);
  }

  checkboxToggle() {
    // state is updated first
    this.setState({ boxIsChecked: !this.state.boxIsChecked });
    console.log("boxIsChecked: " + this.state.boxIsChecked);
    if (this.state.boxIsChecked === false) {
      console.log("box is false. should do nothing.");
    }
    else if (this.state.boxIsChecked === true) {
      console.log("box is true. should be added.");
      this.props.setForDelete(this.props.person._id);
    }

  }

    render() {
        return (
          <div>
            <input type="checkbox" name="person" checked={this.state.boxIsChecked} onClick={this.checkboxToggle} />
            {this.props.person.name} ({this.props.person.age})
          </div>
        );
    }
}

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

我尝试过onChange而不是onClick。我觉得我已经从这里这里开始阅读有关基本成分配方的建议。我是否将Redux用于其他值是否会影响任何事情?有没有一种方法可以只读取复选框,而不是尝试对其进行控制?(复选框本身可以正常工作,并且无论是否正确检查DOM,它都会更新。)

Nab*_*hah 15

我知道该线程已得到回答,但我也有一个解决方案,您看到复选框未使用 setState 提供的值更新,我不知道此问题的确切原因,但这里有一个解决方案。

<input
  key={Math.random()}
  type="checkbox"
  name="insurance"
  defaultChecked={data.insurance}
 />
Run Code Online (Sandbox Code Playgroud)

通过提供 random 的键值,复选框会重新呈现并更新复选框的值,这对我有用。我也在使用钩子,但它应该适用于基于类的实现。

参考:https : //www.reddit.com/r/reactjs/comments/8unyps/am_i_doing_stupid_or_is_this_a_bug_checkbox_not/


Bat*_*lug 12

setState() 确实没有立即反映出来:

在文档中阅读此处

setState() 将组件状态的更改加入队列,并告诉 React 该组件及其子组件需要使用更新后的状态重新渲染。这是您用来更新用户界面以响应事件处理程序和服务器响应的主要方法。

将 setState() 视为更新组件的请求而不是立即命令。为了获得更好的感知性能,React 可能会延迟它,然后一次更新多个组件。React 不保证状态更改会立即应用。

setState() 并不总是立即更新组件。它可能会批量更新或推迟更新。这使得在调用 setState() 之后立即读取 this.state 成为一个潜在的陷阱。相反,使用 componentDidUpdate 或 setState 回调 (setState(updater, callback)),这两者都保证在应用更新后触发。如果您需要根据之前的状态设置状态,请阅读下面的更新程序参数。

setState() 将始终导致重新渲染,除非 shouldComponentUpdate() 返回 false。如果正在使用可变对象并且在 shouldComponentUpdate() 中无法实现条件渲染逻辑,则仅在新状态与先前状态不同时调用 setState() 将避免不必要的重新渲染。

这里有一些实验

所以最好捕获事件并检查它,而不是依赖于this.setState() 类似的东西:

handleChange: function (event)  {
   //you code
    if (event.target.checked) {
      console.log("box is true. should be added.");
      this.props.setForDelete(this.props.person._id);
    }

  }
Run Code Online (Sandbox Code Playgroud)

    render() {
            return (
              <div>
                <input type="checkbox" name="person" checked={this.state.boxIsChecked} 
                   onChange={this.handleChange.bind(this)}/>
                {this.props.person.name} ({this.props.person.age})
              </div>
            );
        }
Run Code Online (Sandbox Code Playgroud)