[英]React Conditional routing with Navigate and useState
I need help figuring out something.我需要帮助弄清楚一些事情。
I have the following React app:我有以下反应应用程序:
function App() {
const [walletConnected, setWalletConnected] = useState("")
async function checkConnection() {
const accounts = await window.ethereum.request({ method: 'eth_accounts' })
if (accounts.length > 0) {
setWalletConnected(true)
} else {
setWalletConnected(false)
}
}
return (
<>
<Router>
<Routes>
<Route exact path='/' element={<Home/>}/>
<Route exact path='/signin' element={<SignInPage/>}/>
<Route exact path='/generator' element={<GeneratorPage/>}/>
<Route exact path='/ethers' element={<Ethers/>}/>
<Route exact path='/connected' element={<GeneratorPage/>}/>
{checkConnection() && <Route
exact
path="/gated"
element = {walletConnected ? <GeneratorPage/> : <Navigate to="/" />} />
}
</Routes>
</Router>
</>
);
}
What I am basically trying to implement is conditional routing.我基本上试图实现的是条件路由。 But it doesn't work in it's current form.
但它不能以目前的形式工作。
What's interesting is, if I don't use <Navigate to= />
but instead render a page element, the code works fine and I get the page to render correctly.有趣的是,如果我不使用
<Navigate to= />
而是渲染页面元素,那么代码可以正常工作并且我可以正确渲染页面。
It seems what is happening is that the condition doesn't get switched fast enough, and React instantly navigates to the page, without giving a chance for <GeneratorPage/>
to render.似乎正在发生的事情是条件切换得不够快,React 立即导航到页面,而没有给
<GeneratorPage/>
呈现的机会。
You are checking the condition like this你正在检查这样的条件
checkConnection() && <Route ....
but your checkConnection()
method doesn't return anything.但是您的
checkConnection()
方法不返回任何内容。
You can call the checkConnection()
inside an useEffect您可以在 useEffect 中调用
checkConnection()
useEffect( () => {
checkConnection()
},[])
and modify the code like this并像这样修改代码
<Route
exact
path="/gated"
element = {walletConnected ? <GeneratorPage/> : <Navigate to="/"
/>
.. other routes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.