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

6

所以,我有一个带有多个输入的表单,这些输入在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});
  }
} 

问题:
当用户设置标题和描述后,isApproved会变为true(我想要的)。 但是,如果用户将标题更改为“” ,则批准仍然保持为true(不是我想要的)。 如果用户开始键入描述,那么批准开关将切换到false。 我认为这与组件生命周期以及状态何时被设置有关,但我不确定。
我不介意使用jQuery来检查验证,但我希望只需在输入更改后检查值,然后使用方法和props更新邮政编码。
在各个输入字段中使用onChange事件处理程序更新状态对象并进行验证的最佳实践方法是什么?
最终,如果存在任何无效输入,则isApproved应为false。

你的文本框下面有提交按钮吗? - zenwraight
当我在文本框中输入标题,然后应该点击按钮来设置它,就像这样。 - zenwraight
1个回答

7
请在 setState 回调函数的第二个参数中运行帖子批准测试。 正如您已经注意到的 - setState 方法是异步的,组件状态不会立即更新。
this.setState({post}, this.checkPostApproval)

请查看React文档中关于setState的说明的注释:

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


我想你的意思是这样的 - this.setState({post: post}, this.checkPostApproval);? - zenwraight
2
这个语法是等价的。请查看对象属性简写的原因。两者都应该可以工作。 - Przemysław Zalewski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接