我正試圖在我的專案中實施一個認證系統,并且一直在遵循這個教程https://youtu.be/LKlO8vLvUao 。 該系統可以正常作業,但是我試圖在登錄失敗時顯示錯誤資訊,而且我無法弄清楚如何將錯誤資訊從還原器中獲取到我想要顯示的組件中(最好使用 [msg,setMsg] 鉤)
。以下是我在動作中的代碼,我在其中捕獲了錯誤回應并將其傳遞給了 reducer:
我在其中捕獲了錯誤回應并將其傳遞給了 reducer。
export const signin = (formData, history)=> async(dispatch)=> {
try {
const { data } = await API.signIn(formData)。
dispatch({ type: AUTH, data })。)
history.push('/')
}
catch (error){
const data = error.response.data。
dispatch({ type: "AUTH_FAIL"/span>, data })
}
}
這是我的還原器:
import { AUTH, LOGOUT } from '.../constants/actionTypes'
const authReducer =(state = { authData: null }, action) => {
switch(action.type){
case AUTH:
localStorage.setItem('profile',JSON。 stringify({ ...action?.data })
return { ...state, authData: action?.data};
case LOGOUT:
localStorage.clear()。
return { ...state, authData: null }。
case "AUTH_FAIL"/span>:
return { ...state, authData: action?.data};
default:
return state。
}
}
export default authReducer;
uj5u.com熱心網友回復:
在你為這個還原器定義狀態的地方,把它分成兩個部分。一個是現在的authData,第二個是錯誤。當調度AUTH_FAIL時,你應該在還原器中回傳的是錯誤而不是 authData。現在在你的組件中,你可以隨心所欲地呼叫狀態并使用更新的狀態。我知道有兩種方法可以做到這一點。
1-mapStatetoProps
2-store.subscribe()和store.getState()
uj5u.com熱心網友回復:
在Reducer中創建initiateState物件
const initiateState: {
authData: null,
error: null。
正如你在行動中所做的那樣
catch (error){
**const data = data.response.error; **
dispatch({ type: "AUTH_FAIL"/span>, data })
}
同時改變reducer,并將action.data的數量發送到error
const authReducer=(state = initiateState, action)=> {
....//your code。
case "AUTH_FAIL"/span>:
return { ...state, error: action.data};
default:
return state。
}
}
使用Hooks
this等于mapStateToProps
const error= useSelector((state) => /span> state。 error)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333310.html
標籤:
