React:react-datepicker 不会更新状态

React: react-datepicker won't update state

我正在尝试对日期选择器进行更改,但状态没有更新。我正在使用道具的状态。所以日期已经存在。它显示过期日期。当我进行更改时,它会卡在当前日期。

我在 onChange 处理程序中遗漏了什么?

  constructor(props) {
    super(props);

    const {export} = this.props;
    this.state = {showCalender: false};
    this.date = export.expires;

    this.handleChange = this.handleChange.bind(this);
  }

  static getDerivedStateFromProps(props, state) {
    if (props.export.expires !== state.expires) {
      return {
        expires: props.export.expires
      };
    }
    return null;
  }

  handleChange(date) {
    this.setState({
      expires: date
    }, console.log(this.state.expires));
    this.handleClick();
  }

  handleClick() {
    this.setState({showCalender: !this.state.showCalender});
  }

  handleClear() {
    this.setState({expires: ''});
  }

  render() {
    const {expires, showCalender} = this.state;
    const expiresDate = format(expires, 'MM/dd/yyyy');

    return (
        <div>
          <FormGroup>
            <FormControl
              id="date"
              value={expiresDate}
              onChange={this.handleChange}
              onClick={() => this.handleClick()}
              title="set date"
              aria-label="set date"
            />
            <Button className="close-btn" onClick={() => this.handleClear()}>Clear</Button>
          </FormGroup>
          { showCalender && (
            <FormGroup>
              <DatePicker
                selected={expires}
                onChange={this.handleChange}
                inline
              />
            </FormGroup>
          )}
      </div>
    );
  }

当您更新状态时,您将触发重新渲染,但就在下一次渲染之前,React 正在调用 getDerivedStateFromProps,您将在那里检查值是否不同:

static getDerivedStateFromProps(props, state) {
    if (props.export.expires !== state.expires) {
      return {
        expires: props.export.expires
      };
    }
    return null;
  }

它们是什么,因为您刚刚更新了 stateprops 保持不变。 然后你再次更新状态,但现在你将它设置回 props 中的任何值。

来自DOCS

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates.

我不确定您为什么要尝试同步 props 和状态,但这通常表明您的应用设计不当。

如评论中所述,自 ES2015 以来,请勿使用名为 export 的变量作为保留字。

您可能会遇到以下错误:

Unexpected keyword 'export'