简体   繁体   English

如何正确组合 useState 和 useEffect

[英]How to combine useState and useEffect properly

I want to compare 2 inputs value.我想比较 2 个输入值。 The typical password/repeat password input in a form.表单中输入的典型密码/重复密码。

Using onChange react useState render the DOM but not immediately because I shopuld use useEffect.使用 onChange react useState 呈现 DOM 但不是立即呈现,因为我应该使用 useEffect。

But I'm not sure how to combine both.但我不确定如何将两者结合起来。 I'm conscious there is other answers replying something similar but I can't apply to this case.我知道还有其他答案可以回答类似的问题,但我不能适用于这种情况。

This is my useSstate :这是我的使用状态

 const [user, setUser] = useState({
        username: '',
        password: '',
    });

This is my onInputChange function :这是我的 onInputChange function

const onInputChange = (e) => {
        if ((e.target.id === 'password') === (e.target.id === 'confirmPassword')) {
            console.log('Match!')
        } else {
            console.log('DO NOT Match')
        }
        setUser({ ...user, [e.target.name]: e.target.value });
        console.log('User Updating values: ', user)
    }

This is the input (MUI textfield) :这是输入(MUI 文本字段)

    <TextField
      id="password"
      name="password"
      label="Password"
      type="password"
      onChange={(e) => onInputChange(e)}
    />
                                                
<TextField
      id="confirmPassword"
      name="confirmPassword"
      label="Confirm password"
      type="password"
      onChange={(e) => onInputChange(e)}
 />

Could you help me with this, please?你能帮我解决这个问题吗?

Here you can find how it works在这里你可以找到它是如何工作的

CodeSandBox代码沙盒

This is not best practice because you should match password on submit or on blur event trigger on each input.这不是最佳做法,因为您应该在提交时匹配密码或在每次输入时触发模糊事件。

Ask me if you need furthur help !问我是否需要进一步的帮助!

Thank You.谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM