thunk 和 action 完成后如何使用 redux 的当前状态?
Posted
技术标签:
【中文标题】thunk 和 action 完成后如何使用 redux 的当前状态?【英文标题】:How can I use the current status of redux after the thunks and actions have finished? 【发布时间】:2021-08-05 02:40:04 【问题描述】:在 thunk 和 action 完成后,如何使用 redux 的当前状态?问题出在 handleSubmit 函数中,如果我注册一个有错误的用户,它会使用消息“电子邮件已注册”更新 redux 的状态,但是当访问调度承诺中的状态时,会向我发送一个错误的状态,没有消息。
函数处理提交
const handleSubmit = (e) =>
e.preventDefault()
const form =
name: e.target[0].value,
email: e.target[1].value,
password: e.target[2].value,
confirmPassword: e.target[3].value
const name, email, password = form
if (isFormValid(form))
//TODO: FIX IT synchronize redux with errors
dispatch( startRegisterUser(name, email, password) ).then(() =>
console.log(state)
)
注册动作和重击
export const startRegisterUser = (name, email, password) =>
return (dispatch, state) =>
dispatch(startLoadingAction())
return firebase.auth().createUserWithEmailAndPassword(email, password)
.then(async ( user ) =>
await user.updateProfile(
displayName: name,
photoURL: ''
)
dispatch(registerUserAction(user.uid, user.displayName))
)
.catch(e =>
if (e.code === "auth/email-already-in-use")
dispatch(errorAction("Email already registered"))
else
dispatch(errorAction("Unexpected error"))
)
.then(() =>
dispatch(finishLoadingAction())
console.log("finished dispatch's", state())
return
)
export const registerUserAction = (uid, displayname) =>
return
type: types.register,
payload:
uid,
displayname
控制台日志 我想获取第一个控制台日志的状态,但是在 handlesubmit 函数中
【问题讨论】:
【参考方案1】:您应该在 reducer 中处理 errorAction
,使用错误消息更新 ui
存储切片。并且,您需要在 thunk 函数的 promise 中返回 state()
。然后,您将在 handleSubmit
事件处理程序中获得整个状态。
例如
import applyMiddleware, createStore from 'redux';
import thunk from 'redux-thunk';
function errorAction(message)
return
type: 'ERROR',
payload: message,
error: true,
;
export const startRegisterUser = (name, email, password) =>
return (dispatch, state) =>
return Promise.reject( code: 'auth/email-already-in-use' )
.catch((e) =>
if (e.code === 'auth/email-already-in-use')
dispatch(errorAction('Email already registered'));
else
dispatch(errorAction('Unexpected error'));
)
.then(() => state());
;
;
export const registerUserAction = (uid, displayname) =>
return
type: 'REGISTER',
payload:
uid,
displayname,
,
;
;
function rootReducer(state = ui: error: '' , action)
switch (action.type)
case 'ERROR':
return ui: error: action.payload ;
default:
return state;
const store = createStore(rootReducer, applyMiddleware(thunk));
function handleSubmit()
store
.dispatch(startRegisterUser('name', 'example@gmail.com', '123') as any)
.then((state) =>
console.log('handleSubmit state: ', state);
);
// triggered by user submit event
handleSubmit();
输出:
handleSubmit state: ui: error: 'Email already registered'
【讨论】:
以上是关于thunk 和 action 完成后如何使用 redux 的当前状态?的主要内容,如果未能解决你的问题,请参考以下文章
getState 和 dispatch 如何在 redux-thunk action creator 中导入?