【问题标题】:react setState change hour using moment使用时刻反应 setState 更改小时
【发布时间】:2023-03-11 17:19:01
【问题描述】:

我在 moment.js 中设置小时有问题,状态似乎需要一点延迟来解决时间才能改变状态。

我的事件处理程序如下所示

handleKeyDownPickerInput(e, type) {
    let input = e.target.value;

      if (!input || isNaN(input)) return;

      if (type === "hour") {
        this.setState({
          currentTime: moment(this.state.currentTime).set({ h: input })
        });
      }
  }

https://codesandbox.io/s/w22m3wnj4l

【问题讨论】:

    标签: javascript reactjs ecmascript-6 momentjs


    【解决方案1】:
    this.setState({
        currentTime: moment(this.state.currentTime).set({ h: input })
    });
    

    setState 方法异步运行,因此您不能依赖“this.state”,因为它可能无法读取当前状态。

    this.setState((previousState) => ({
            currentTime: moment(previousState.currentTime).set({ h: input })
        })
    );
    

    请注意,setState 方法将匿名函数作为第一个参数,您可以读取之前的状态。

    这是你应该写的方式。

    仅供参考: State Updates May Be Asynchronous

    【讨论】:

    • 另一种方法就是改成onChange而不是keyDown
    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2018-01-17
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2020-05-27
    相关资源
    最近更新 更多