javascript - ReactJS setState 不适用于复选框的第一个切换

标签 javascript reactjs react-native

有什么原因 setState 不会运行重新渲染?我使用了 console.log 回调来检测状态是否已更改,但无济于事。

这是我正在使用的代码。还有更多这样的状态是函数调用的 bool,但函数的基础知识在这里。

export class ExampleClass extends React.Component {
constructor(props) {
  super(props);
    this.state = {
      usingToggleOne: false
    };
  }
}
toggleforToggleOne(event) {
  this.setState({
    usingToggleOne: !this.state.usingToggleOne,
  }); 
}

render() {
  return(
    <input type="checkbox"
                   onChange={this.toggleforToggleOne.bind(this)} />
}

我会第一次点击复选框,它会打勾,但状态不会改变,但之后它会正常工作。有什么理由吗?我很幸运地使用 Object.assign 让第一个滴答开始工作,但我宁愿不使用它,因为它会改变状态。

最佳答案

render()componentDidUpdate() 方法中尝试 console.log(),如下面的代码和这个代码笔:http://codepen.io/PiotrBerebecki/pen/ZpLNZd

您还可以使用传递给“setState”的可选回调函数访问新状态。更多信息在这里:http://reactkungfu.com/2016/03/dive-into-react-codebase-handling-state-changes/#solving_the_validation_problem

状态 bool 每次勾选/取消勾选时都会改变。

此外,请注意 React 文档中的以下内容:https://facebook.github.io/react/docs/component-api.html#setstate

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

class ExampleClass extends React.Component {
  constructor() {
    super();
    this.state = {
      usingToggleOne: false
    };

  }

  toggleforToggleOne(event) {
    console.clear();
    console.log('check in toggle before set state', this.state.usingToggleOne);
    this.setState({
      usingToggleOne: !this.state.usingToggleOne
    }, function afterStateChange () {this.useNewState();});
    console.log('check in toggle after set state', this.state.usingToggleOne);
  }

  useNewState() {
    console.log('check in useNewState callback', this.state.usingToggleOne);
  }

  componentWillUpdate() {
    console.log('check in componentWillUpdate', this.state.usingToggleOne);
  }

  componentDidUpdate() {
    console.log('check in componentDidUpdate', this.state.usingToggleOne);
  }

  render() {
    console.log('check in render', this.state.usingToggleOne);
    return(
      <input type="checkbox"
             onChange={this.toggleforToggleOne.bind(this)} />
    );
  }
}

关于javascript - ReactJS setState 不适用于复选框的第一个切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39655205/

相关文章:

javascript - 检测 redux 存储更改

reactjs - 将构建的 React 应用程序静态文件部署到 Cloud Foundry 似乎认为它是一个 Node 部署,即使使用 buildpack

node.js - 有关如何为聊天应用程序设计良好架构的建议?

javascript - 平面列表延伸到屏幕之外

javascript - 远程 javascript 文件上的 jquery 单击监听器

javascript - jquery 悬停在 firefox 中不起作用

typescript - 使用 Typescript 和 JSX 响应事件处理程序

react-native - 显示键盘后滚动到 FlatList 的末尾

android - 如何检查联系人是否下载了我的应用程序?

javascript - 了解 Angular 数据绑定(bind)