在较旧的 React Router Dom 版本中,如果用户登录,我可以使用此代码进行重定向:
history.push('/login?redirect=shipping')
Now in v6,
我正在使用useNavigate
函数而不是history.push
,但它不起作用,因为它带我去/login/shipping
代替/shipping
。目前,这是我的导航代码:
let navigateCart = useNavigate()
// some code here
navigateCart('/login?redirect=shipping') // the mistake is inside the parenthesis here but I don't know what it is!
这是我的路由器配置:
<BrowserRouter>
<Container>
<Routes>
<Route path="/" element={<HomeScreen />} exact />
<Route path="/login" element={<LoginScreen />} />
<Route path="/profile" element={<ProfileScreen />} />
<Route path="/shipping" element={<ShippingScreen />} />
</Routes>
</Container>
</BrowserRouter>
登录屏幕功能:
function LoginScreen() {
let navigateLog = useNavigate()
let location = useLocation()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const dispatch = useDispatch()
const redirect = location.search ? location.search.split('=')[1] : '/'
const userLogin = useSelector(state => state.userLogin)
const { error, loading, userInfo } = userLogin
useEffect(() => {
if (userInfo) {
navigateLog(redirect)
}
}, [navigateLog, userInfo, redirect])
const submitHandler = (e) => {
e.preventDefault()
dispatch(login(email, password))
}