React 复选框不更新

React Checkbox Does Not Update

我想在每次将复选框切换为 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;

我试过 onChange 而不是 onClick。我觉得我已经在遵循我从 and here 中读到的有关基本组件公式的建议。我将 Redux 用于其他值这一事实会影响什么吗?有没有办法只读取复选框是什么,而不是试图控制它? (复选框本身工作正常,DOM 会更新它是否被正确选中。)

您无法在调用 setState() 后立即访问 state 的更新值。

如果你想用更新的状态值做一些事情,你可以这样做。即在 setState() 回调函数中

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


});

setState()确实没有马上反映出来:

Read here in the docs:

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

setState() will always lead to a re-render unless shouldComponentUpdate() returns false. If mutable objects are being used and conditional rendering logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

and here some experiments

所以捕获事件并检查它可能会更好,而不是依赖于 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);
    }

  }

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

我知道这个帖子已得到解答,但我也有解决方案,您看到复选框没有更新为提供的 setState 值,我不知道这个问题的确切原因,但这里是一个解决方案。

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

通过给随机键值,复选框被重新渲染并且复选框的值被更新,这对我有用。我也在使用钩子,但它应该适用于基于 class 的实现。

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

我来到这里是想弄清楚为什么我的复选框(使用 HTM 标记的模板库呈现)无法正常工作。

return html`
  ...
  <input type="checkbox" checked=${state.active ? "checked" : null} />
  ...
`;

事实证明,我只是对那个三元运算符太用力了。这很好用:

return html`
  ...
  <input type="checkbox" checked=${state.active} />
  ...
`;

React 解决方案:

HTML:

<input type="checkbox" ref={checkboxRef} onChange={handleChange}/>

JS:

const checkboxRef = useRef("");
  const [checkbox, setCheckbox] = useState(false);
  const handleChange = () => {
    setCheckbox(checkboxRef.current.checked);
  };

现在您的 true/false 值存储在复选框变量中

展开没有新手回答;什么对我有用:

  • 从 onChange Event-Listener 中删除 preventDefault() 但这对我来说不合适,因为我只想对更新值做出反应。它可能并不适用于所有情况,例如 OP。
  • 在键中包含选中的值,如 key={"agree_legal_checkbox" + legalcheckboxValue} checked={legalcheckboxValue}

我从新手的回答中得到了这两个解决方案,但是有一个 math.random 键感觉不对。使用 checked 的值会导致键仅在 checked 值也发生变化时发生变化。

(没有足够的声誉来简单地 post 这作为评论,但仍然想分享)