【发布时间】:2023-02-19 07:08:38
【问题描述】:
在较旧的 React Router Dom 版本中,如果用户已登录,我可以使用此代码进行重定向:
history.push('/login?redirect=shipping')
现在在 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 dont 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))
}
【问题讨论】:
-
显示您的路由器配置
-
@KonradLinkowski 好了!它正在为其他路线工作!
-
@KonradLinkowski 如果您需要更多代码,请告诉我
-
@bysEcode 你声明了
navigate然后使用了navigateCart,这正常吗? -
您在
LoginScreen组件内获取参数redirect=shipping并进行我假设的重定向,如果是这样,您可以通过LoginScreen的代码吗?
标签: javascript reactjs react-router react-router-dom