[英]How would I attach a randomly generated string to react router useParams()?
我的問題解釋:
基本上我正在嘗試創建一個多人 web 游戲。 在嘗試了解如何在“開始新游戲”時打開新頁面時,我遇到了一個邏輯問題。
我想通過 function 隨機生成一個字符串,然后在我的 url 中將該結果用作:id。 我可以成功創建隨機生成的字符串,但仍然對如何在我的 useParams() for react-router v5 中使用它感到困惑。
如果可能的話,我還想將一個套接字連接到每個生成的 url ,這樣它就可以輕松地解決問題並且一切都保持原位。
所以它會在頁面的邏輯中
如果您對處理此問題的其他方法有任何其他見解,將不勝感激!
我的代碼
應用程序.jsx
import React from 'react';
import Landing from './Landing/Landing.jsx';
import Game from './Game/Game.jsx';
import { HashRouter as Router, Switch, Route } from 'react-router-dom';
import './Styles/styles.scss';
const App = () => {
return (
<Router>
<Switch>
<Route exact path="/" component={Landing} />
<Route exact path="/game/:id" component={Game} />
</Switch>
</Router>
)
}
export default App
登陸.jsx
import React, {useEffect, useState} from 'react';
import { useParams } from 'react-router-dom';
const Landing = () => {
const { id } = useParams();
const [randomRoom, setRandomRoom] = useState('');
/*
This functions needs to create :id for react-router and also create room id for socket.io
*/
const getRandomString = (length) => {
let randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for ( let i = 0; i < length; i++ ) {
result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
}
setRandomRoom(result)
}
return (
<div>
<button onClick={() => {
getRandomString(20);
}}>
Start New Game
</button>
</div>
)
}
export default Landing
游戲.jsx
import React from 'react'
const Game = () => {
/*
This will hold the content for game page including Map, scoreboard, usernames, list of items, etc
*/
return (
<div>
HELLO FROM GAME
</div>
)
}
export default Game
由於 url /game/:id
呈現Game
組件,因此您需要使用useParams
來獲取該 URL 參數的值。
所以你的Game
代碼將如下所示:
const Game = () => {
const { id } = useParams();
return (
<div>
HELLO FROM GAME
</div>
)
}
然后,您可以將該 ID 用於您想到的任何目的。
您可以使用react-router-dom
的Link
組件解決此問題,並將to
屬性設置為所需的 URL (包括:id
部分)。
然后,您可以從新頁面發出網絡請求,使用useParams
提取 URL 的id:
部分:
/// first-page.jsx
export const FirstPage = () => {
const getRandomString = useCallback(() => {
// generate your string...
return 'your_random_string';
}, []);
return (
<>
<div>Some other components ...</div>
<Link
to={`/second/page/:${getRandomString()}`}
>
Start Game!
</Link>
</>
);
};
/// second-page.jsx
export const Secondpage = () => {
const { id } = useParams();
return (
<div>The page's ID is: {id}</div>
);
};
/// index.jsx
ReactDOM.render(
<Router>
<Switch>
<Route exact path="/first/page">
<FirstPage />
</Route>
<Route path="/second/page/:id">
<SecondPage />
</Route>
</Switch>
</Router>
);
如果您查看最后一個片段中的路線,您會看到 URL 的最后一個片段由 react-router 標識為:id
。 這與第一頁中使用的模式匹配,然后可以由第二頁中的useParams
讀取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.