redux-form的新用户。我有一个登录模式,该模式具有2种不同的操作:登录和注册。默认情况下,该角色(存储在组件状态中)为login
,并且用户可以单击按钮将其更改为register
。
我遇到的麻烦是,我想将该状态传递给onSubmit()
函数,以便我可以根据用户是否尝试登录或注册来调度正确的操作。
我的想法是我可以将这种称为 signInType 的状态传递给该函数。当然,它没有按我预期的那样工作。我可以通过reduxForm HOC传递属性,但是从该函数中我无法访问组件的状态。
以下是我组件的相关部分,以帮助了解我的最终目标是什么:
const [signInType, setSignInType] = useState('login')
const onSubmit = (data, dispatch, props) => {
console.log('props: ', props);
if (props.signInType === 'login') {
return (
api.post('/Login', data)
.then(json => {
const response = JSON.parse(json.d)
if (!response.userid) {
console.error(response.message)
dispatch(emailLoginFailure(response.message))
return response.message
}
LogRocket.identify(response.userid, {
email: data.email,
})
dispatch(emailLoginSuccess(response))
})
.catch(err => {
console.error(err)
dispatch(emailLoginFailure(err))
})
)
} else if (props.signInType === 'register') {
return (
api.post('/RegisterByEmail', {
email: data.email,
password: data.password,
utm_source: "Development",
utm_medium: "email",
utm_campaign: "Campaign Test",
utm_term: "N/A",
utm_content: "123",
utm_date: "2019-02-11 12:25:36"
})
.then(json => {
const response = JSON.parse(json.d)
if (!response.userid) {
console.error(response.message)
dispatch(emailRegisterFailure(response.message))
return response.message
}
// LogRocket.identify(response.userid, {
// email: data.email,
// })
dispatch(emailRegisterSuccess(response))
})
.catch(err => {
console.error("Unable to register email:", err)
})
)
} else {
console.error("error: No signin type?")
}
}
感谢您的帮助:)
答案 0 :(得分:1)
这样的登录/注册流程我更喜欢用不同的组件来处理,以便遵守并遵循SRP。
此外,我不确定您如何组织组件,但这是我如何处理这种情况:
您的模式:
* 它将仅负责呈现“登录”或“注册”表单。
training_iteration
登录表单:
* 现在,您可以将登录操作传递给const Modal = () => {
const [signInType, ] = useState('login')
const isLogin = signInType === 'login'
return <>
{ isLogin ? <LoginForm /> : <RegisterForm /> }
<button onClick={() => setSignInType(isLogin ? 'register' : 'login')}>
{ isLogin ? 'Sign up' : 'Sign in' }
</button>
</>
}
prop 。 onSubmit
将是您的演示文稿组件,而Login
将LoginForm
的HOC装饰为Login
。
reduxForm
RegisterForm:
* 在这里,我们遵循与export default reduxForm({
form: 'login',
onSubmit: data => {}
})(Login)
相同的想法。
LoginForm