我将如何附加随机生成的字符串来响应路由器 useParams()?

问题描述

我的问题解释:

基本上我正在尝试创建一个多人网络游戏。在尝试了解如何在“开始新游戏”时打开新页面时,我遇到了一个逻辑问题。

我想通过一个函数随机生成一个字符串,然后将该结果用作我 url 中的 :id。 我可以成功创建随机生成的字符串,但仍然对如何在 react-router v5 的 useParams() 中使用它感到困惑。


如果可能的话,我还想将一个套接字连接到每个生成的 url,这样它就可以轻松地拆分关注点并且一切都保持原样。


所以它会在页面的逻辑中

  1. 带有开始新游戏按钮的登陆页面
  2. 点击新游戏按钮,新标签页会打开,其中包含与该特定游戏相关的游戏内容

如果您对处理此问题的不同方式有任何其他见解,将不胜感激!


我的代码

App.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

Landing.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

Game.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

Visuals of what I want

解决方法

由于 url /game/:id 呈现 Game 组件,因此您需要使用 useParams 来获取该 URL 参数的值。

因此您的 Game 代码将如下所示:

const Game = () => {
    const { id } = useParams();

    return (
        <div>
            HELLO FROM GAME
        </div>
    )
}

然后你可以将这个 ID 用于你想到的任何目的。

,

您可以使用 react-router-domLink 组件解决此问题,并将 to 属性设置为所需的 URL(包括 :id 部分)。

然后,您可以从新页面发出网络请求,使用 id: 提取 URL 的 useParams 部分:

/// 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 读取。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...