【发布时间】:2023-03-08 08:30:01
【问题描述】:
使用redux-saga 和react router 4。我正在尝试实现用户注册流程。我专注于在/user/register 路线上向用户显示注册屏幕的部分。
目标
目标是在与Alert 相同的屏幕上更新用户注册状态,具体取决于成功创建的用户或已经存在的用户。我正在使用 redux-saga 并使用 saga 中的 history.push 来更新视图。
问题
只有在我重新加载/user/register 页面后才会显示警报。
我从我的传奇中将状态传递给history.push,然后在我的组件中基于我从this.props.location.state 中提取的状态,我准备警报内容。
注册组件
// Form submission handler
handleUserRegistration = user => {
this.props.registerUser(user, this.props.history);
}
// Prepring the alert content
getAlertUI = signupState => {
if (signupState.signupSuccess) {
return <UncontrolledAlert color='success'>{'Verification email sent. Please verify your account.'}</UncontrolledAlert>
}else {
return <UncontrolledAlert color='danger'>{signupState.error.message}</UncontrolledAlert>
}
}
render () {
let alertContent = null;
const signupResponse = this.props.location.state;
if (signupResponse) {
if (signupResponse.error) {
alertContent = this.getAlertUI({signupSuccess: false, error: signupResponse.error});
}else {
if (signupResponse.verificationEmailSent) {
alertContent = this.getAlertUI({signupSuccess: true})
}
}
}
return (
<div> {alertContent} </div>
// My form component goes here.
)
}
虽然是我的saga。我正在使用带有必要信息的history.push。
saga.js
const registerWithEmailPasswordAsync = async (userData) =>
await axios.post(apiUrls.SINGUP_USER, userData )
.then(response => {
return {
isError: false,
data: response.data,
}
})
.catch(error => {
return {
isError: true,
errorDetails: {
status: error.response ? error.response.status : null,
message: error.response ? error.response.data : null,
}
}
})
function* registerUser({ payload }) {
const { history } = payload;
try {
const registerUser = yield call(registerWithEmailPasswordAsync, payload.user);
if (!registerUser.isError) {
history.push('/user/register', {verificationEmailSent: true});
} else {
if (registerUser.errorDetails) {
history.push('/user/register', {error: registerUser.errorDetails} );
}
}
} catch (error) {
console.log('register error : ', error)
}
}
我对此很陌生,请分享这是否是更好的方法?如果是这样,它为什么不更新我的观点。任何指针都受到高度赞赏。
【问题讨论】:
标签: reactjs react-redux react-router-v4 redux-saga