Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

reactjs - 使用React Router,当URL中有参数时如何重定向到路由?(Using React Router, how do I redirect to a route when there is a parameter in the URL?)

I have a React app using react-router-dom and I'd like to create a <Redirect /> in my top level App component if a condition is met.

(我有一个使用react-router-dom的React应用程序,如果满足条件,我想在我的顶级App组件中创建一个<Redirect /> 。)

import { BrowserRouter, Redirect, Route } from 'react-router-dom';

function App() {

  const [user, setUser] = useState(null);

  function noUserRedirect() {
    // redirect to Home if user is empty
    if(!user) {
      return (
        <Redirect to="/" />
      );
    }
  }

  return (
    <BrowserRouter>
      {noUserRedirect()}
      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/dashboard/:id">
        <Dashboard />
      </Route>
    </BrowserRouter>
  );
}

export default App;

I know that user is not set.

(我知道没有设置user 。)

When I visit /dashboard , the redirect works and I am brought to the <Home /> component, but when I visit /dashboard/123 , for example, the redirect function runs, but I am still brought to the <Dashboard /> component.

(当我访问/dashboard ,重定向有效,并且被带到<Home />组件,但是当我访问/dashboard/123 ,例如,重定向功能运行,但是仍然带到<Dashboard />组件。)

How can I prevent that from happening?

(如何防止这种情况发生?)

  ask by Michael Lynch translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why dont you just redirect programatically, like so:

(为什么不以编程方式重定向,就像这样:)



import { BrowserRouter, Redirect, Route } from 'react-router-dom';

function App() {

  const [user, setUser] = useState(null);

  const history = useHistory();

  useEffect(()=>{
    if(!user)
      history.push("/");
  }, [user]);


  return (
    <BrowserRouter>
      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/dashboard/:id">
        <Dashboard />
      </Route>
    </BrowserRouter>
  );
}

export default App;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...