ReactJS:检查状态值并根据状态更新渲染的最佳方法?

Dal*_*ron 5 ecmascript-6 reactjs

所以,我有一个具有多个输入的表单来更新状态onChange.

我想要发生的是让用户更改值,当他们更改时,更新表单state以保存这些更改.我的代码使用ES6类:

super(props);
 this.state = {
   post: this.props.content // this is an object {title: '', description: ''}
 }

 // I have all the methods below this.method = this.method.bind(this) up here.
}

handleTitle(title) { // gets title from input onChange event
  let post = update(this.state.post, {title: {$set: title}}); // using import update from 'immutability-helper' for changing object
  this.setState({ post });
  this.checkPostApproval();
} // this all works, post is updated. I have the same code for description.

checkPostApproval() {
  // here I want to check the post values and make sure they are valid.
  // and either allow or deny submission. 
  if (this.state.post['title'] && this.state.post['description']) {
    this.setState({isApproved: true});
  } else {
    this.setState({isApproved: false});
  }
} 
Run Code Online (Sandbox Code Playgroud)

问题:

当用户设置标题然后设置描述时,isApproved切换为true(我想要的).但是,如果用户随后将标题更改为"",则批准仍然为真(不是我想要的).如果用户然后开始键入描述(批准切换为false).我相信这与组件生命周期和状态设置有关,但我不确定.

我不介意使用jQuery检查验证,但我希望在输入更改后检查值,然后使用方法和道具更新帖子.

更新状态中的对象然后使用onChange各种输入字段中的事件处理程序验证它的最佳实践方法是什么?

最终,isApproved如果有任何无效的输入,我想是假的.

Prz*_*ski 6

请在setState回调中运行后批准测试(第二个参数).正如您已经注意到的那样 - 该setState方法是异步的,组件状态不会立即更新.

this.setState({post}, this.checkPostApproval)
Run Code Online (Sandbox Code Playgroud)

请参阅React文档中有关以下内容的说明setState:

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

  • 这个语法是等价的。请了解原因 - [对象属性简写](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)。两者都应该有效。 (2认同)