简体   繁体   English

react-router-dom 使用导航

[英]react-router-dom useNavigate

I have a component, where i have to call navigate to main page, but navigate is not working, where is my fall?我有一个组件,我必须调用导航到主页,但导航不起作用,我的跌倒在哪里? I know that userName is changing but redirect doesn't happening Index.js我知道用户名正在改变,但重定向没有发生 Index.js

  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>

App.js应用程序.js

  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/login" element={<Login />} />
      <Route path="/settings" element={<Settings />} />
      <Route path="/dashboard" element={<Dashboard />} />
    </Routes>
  )

Login.js登录.js

  const dispatch = useDispatch();
  const user = useSelector((store) => store.user);
  let navigate = useNavigate();
  const onSubmitForm = (e) => {
    e.preventDefault();
    dispatch({
      type: FETCH_USER,
      payload: { login: user.login, password: user.password },
    });
  }

  useEffect(() => {
    if(user.userName) {
      navigate("/login");
    }
  
  }, [user.userName])
  

I am not sure if it is the case but try changing the order of your paths to this:我不确定是否是这种情况,但请尝试将路径的顺序更改为:

return (
    <Switch>
      <Route path="/login" element={<Login />} />
      <Route path="/settings" element={<Settings />} />
      <Route path="/dashboard" element={<Dashboard />} />
      <Route path="/" element={<Home />} />
    </Switch>
  )

I had a similar thing before and somehow navigation was always navigating to the Home because path"/" was on top.我以前有过类似的事情,不知何故,导航总是导航到主页,因为路径“/”在顶部。

Also a small thing, I normally use the Routes with Switch.还有一件小事,我通常使用带有 Switch 的 Routes。 In my experience above structure should work根据我的经验,上述结构应该有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM