【问题标题】:Compare input values (setState) [duplicate]比较输入值(setState)[重复]
【发布时间】:2021-03-01 19:44:12
【问题描述】:

有 2 个处理密码的事件处理程序。 第一个 inputPassword 将其输入中的值写入状态 第二个 inputPasswordRE 写入 input 的值并将其与 inputPassword 中的值进行比较。 由于 setState 是异步工作的,即使输入相同的值,也会检查失败,所以 如何在 inputPasswordRE 中比较其先前状态(当您在密码字段 - 12345 和 re_password 字段 - 12345 中输入时,它们的值 password === re_password 将为 false。)。 如何在 inputPasswordRE 中正确写入 setState 以便 比较是否正确?

const inputPassword = (e) => {
    setState(({ ...state, password: e.target.value }));
  };
  const inputPasswordRE = (e) => {
    setState({ ..state, re_password: e.target.value });
    if (password === re_password) {
      alert(`SUCCESS`)
    } else {alert(`ERROR`)}
  };

【问题讨论】:

  • 您使用的是react hooks 还是基于类的方法?

标签: javascript reactjs react-hooks


【解决方案1】:

你是对的,setState 是异步更新状态,所以它不保证立即改变,你可以使用下面的方法来完成你的任务。

使用基于类

const inputPasswordRE = (e) => {
   this.setState({ ..state, re_password: e.target.value }, (state) => {
      if (state.password === state.re_password) {
        alert(`SUCCESS`)
      } else {
        alert(`ERROR`)
      }
   });
  };

OR

You can also use `componentDidUpdate` as well.

使用 React Hooks

如果您使用react hooks,您可以使用useEffect 来检测更改并进行验证。

useEffect(() => {
 if (password === re_password) {
    // Do your stuff here
 }
}, [password, re_password])

【讨论】:

    【解决方案2】:

    您可以将以下内容用于基于类的组件。

    componentDidUpdate(prevProps, prevState) {
      if (this.state.password === this.state.rePassword) {
        // passwords matched
      } else {
        // passwords didn't match
      }
    }

    您还可以使用带有 useState 挂钩的基于函数的组件。 查看以下代码

    import React, {useState, useEffect} from 'react'
    
    export default function func() {
      const [password, setPassword] = useState('');
      const [rePassword, setRePassword] = useState('');
      
      useEffect(() => {
        if (password === rePassword){
          // passwords matched
        } else {
          // passwords don't match
        }
      })
      return (
        <div>
          <input type="text" name="password" type="password" onClick={(e) => setPassword(e.target.value)} />
          <input type="text" name="password" type="password" onClick={(e) => setRePassword(e.target.value)} />
        </div>
      );
    }

    这应该可以完美运行。

    如果您想知道其他任何内容,请发表评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多