【问题标题】:Where to place dispatch function for useReducer and why?在哪里放置 useReducer 的调度功能,为什么?
【发布时间】:2022-07-22 01:34:15
【问题描述】:

我是 React 新手,目前正在学习 useReducer。 我创建了一个简单的登录功能,用于验证用户输入的电子邮件是否包含“@”并且密码长度是否大于 5。 如果满足这两个条件,我希望我的程序在按下提交按钮时显示成功或失败消息的警报。

我很好奇的是,当我在 useEffect 中添加 dispatch({type: 'isCredValid')} 时,应用程序在提交时显示“成功”(在下面的代码中注释掉),但当我添加 dispatch({type: 'isCredValid'}) 时应用程序显示“失败”在 onSubmit 处理程序中不使用 useEffect。在没有 useEffect 帮助的情况下,在 onSubmit 处理程序中添加 dispatch({type: 'isCredValid')} 时,我希望应用程序显示“成功”。为什么不显示“成功”?以及为什么我的应用在派发函数在useEffect中时会显示“Success”?

减速机功能:

const credReducer = (state, action) => {
    switch(action.type) {
        case 'email' :
            return {...state, email: action.value, isEmailValid: action.value.includes('@')};
        case 'password' :
            return {...state, password: action.value, isPasswordValid: action.value.length > 5 ? true : false};
        case 'isCredValid' :
            return {...state, isCredValid: state.isEmailValid && state.isPasswordValid ? true : false};
        default :
            return state;
    }
}

组件和输入处理程序

const Login = () => {

    const [credentials, dispatch] = useReducer(credReducer, {
        email: '',
        password: '',
        isEmailValid: false,
        isPasswordValid: false,
        isCredValid: false
    })

    // useEffect(() => {
    //     dispatch({type: 'isCredValid'})
    // }, [credentials.isEmailValid, credentials.isPasswordValid])

    const handleSubmit = (e) => {
        e.preventDefault()
        dispatch({ type: "isCredValid" })

        if (credentials.isCredValid === true) {
            alert ("Success!")
        } else {
            alert ('failed')
        }
    }

    const handleEmail = (e) => {
        dispatch({ type: "email", value: e.target.value })
    }

    const handlePassword = (e) => {
        dispatch({ type: "password", value: e.target.value })
    }

  return (
    <Card className={classes.card}> 
        <h1> Login </h1>
        <form onSubmit={handleSubmit}>
            <label>Email</label>
            <input type="text" value={credentials.email} onChange={handleEmail}/>
            <label>Password</label>
            <input type="text" value={credentials.password} onChange={handlePassword}/>
            <button type="submit"> Submit </button>
        </form>

    </Card>
  )
}

【问题讨论】:

  • dispatch 是一个异步函数,不会完成,您也不会在函数句柄提交中看到状态正在更新。如果你想捕捉它何时成功,你可以使用一个 useEffect 来监视状态变化

标签: reactjs react-hooks use-effect use-reducer


【解决方案1】:
 if (credentials.isCredValid === true) {
            alert ("Success!")
        } else {
            alert ('failed')
        }

您可能指的是您没有立即看到“成功”的上述警报。这种情况不会发生,就像状态一样,当你发送一些东西时,你会在下一次渲染时看到更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多