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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…