在使用 Redux Thunk 执行异步操作后,我了解了 2 种重定向到不同页面的方法:
1-方法:将“历史”对象作为参数传递给异步操作。
在您的组件中,您使用“useHistory”钩子定义“历史”对象并将其传递给您的异步操作:
function Register(){
const history = useHistory()
const dispatch = useDispatch()
function registerHandler(){
dispatch(registerAsync(registerForm, history))\
}
return (
// JSX Code
<button onClick={registerHandler}>Register</button>
)
}
然后在您的异步操作中,您可以使用“history.push()”重定向:
export function registerAsync(data, history){
return async function (dispatch) {
try {
const response = await Axios.Post('api/register/', data)
history.push('/register_success')
} catch (e) {
dispatch(registerError(e))
}
}
}
2-方法:使用根据 Redux 存储值有条件地呈现的 <Redirect> 组件:
如果存储值为真,则在组件中有条件地返回:
function Register(){
const dispatch = useDispatch()
const registerSuccess = useSelector((store) => store.auth.registerSuccess)
function registerHandler(){
dispatch(registerAsync(registerForm, history))\
}
if (registerSuccess) {
return <Redirect push to="/register_success"/>
}
return (
// JSX Code
<button onClick={registerHandler}>Register</button>
)
}
在我们的 Async 操作中,我们调度了一个将“registerSuccess”设置为 true 的操作:
export function registerAsync(data){
return async function (dispatch) {
try {
const response = await Axios.Post('api/register/', data)
dispatch(registerSuccess())
} catch (e) {
dispatch(registerError(e))
}
}
}
减速器:
case actionTypes.REGISTER_SUCCESS:
newState.registerSuccess = true
return newState
有谁知道这两种方法中哪一种是正确的,为什么?
非常感谢!