-1

这个功能:

 handleChange(e) {
    this.setState({
      [e.target.name] : e.target.value,
      displayName: (this.state.firstName.substring(0,2)) + (this.state.lastName.substring(0,2)),
      orderNo: (this.props.children.length + 1).toString(),
      sortBirthDate: this.state.birthDate ? new Date(this.state.birthDate).toISOString() :this.state.birthDate ,
      userId: "8e1d8d"
    });
  }

正确返回所有内容,除了 sortBirthDate:

birthDate: "09/21/2014"
displayName: "dsda"
firstName: "ds"
lastName: "da"
orderNo: "5"
sortBirthDate: "0201-09-21T05:50:36.000Z"

我尝试使用 substring 方法删除零,但返回的年份只有 3 位数。

有人看到我在这里缺少什么吗?

先感谢您!

4

1 回答 1

0

问题在于 setState 是异步的。

这是有效的:

  handleChange(e) {
    this.setState({[e.target.name] : e.target.value}, () => {
      this.state.displayName = (this.state.firstName.substring(0,2)) + (this.state.lastName.substring(0,2));
      this.state.orderNo = (this.props.children.length + 1).toString();
      this.state.sortBirthDate = this.state.birthDate ? new Date(this.state.birthDate).toISOString() :this.state.birthDate;
      this.state.userId = "8e1d8d";
    });
  }
于 2020-06-16T20:42:13.133 回答