简体   繁体   中英

How to Use URL Parameters in React?

In my project, when I simply click the 'join room' button on the home page, it directs me to a specific room. So the room number as an example; It happens xPOgk21523aqPW and it does this with an extension like localhost: 3000 / room / xPOgk21523aqPW. When I make this redirect, the name of the component I am in is Player. What I want is to be able to use the code 'xPOgk21523aqPW' in Player.js as a variable when I redirect Homapage.js to Player.js. So every time I redirect, I try to do this by separating the url while the component opens. I tried to transfer data from the component to another component, but for this I could not set up my project on a proper system basis. So how can I apply this method?

In homepage.js xPOgk21523aqPW = room.id

Homepage.js

 <GridItem
        colStart={"auto"}
        colSpan={[5, null, null, 2, null, null]}
        p={6}
      >
        <Heading as="h1" mb={6}>
            Rooms
            </Heading>
            <Divider orientation="horizontal" />
           {rooms.map((room)=> (
              <ListItem>
              <ListItemText primary={room.roomName} secondary={room.roomInfo}
              />
               {/* <Link to={`/room/${room.id}`}></Link> */}
                <Link to={`/room/${room.id}`}>
                <Button onClick={() => joinRoom(room.id)}>Join Room</Button>
                {/* <Form action='localhost:8888?roomId=' method="post">
                <input type="hidden" name="roomCodeTxt" value=room.id />
                <input type="submit" value="Join Room" />
                </Form> */}      
                </Link>
              </ListItem>))}
       </GridItem>

Player.js

class Player extends Component {
  constructor(){
    super();
    const params = this.getHashParams(); 
    let {id} = useParams();
    console.log(id);
    this.state = {
      logeedIn : params.access_token ? true : false,
      currentStatus: false,
      roomId: "",
      rooms: {
      roomAdminMail: "",
      roomName: "",
      roomInfo: ""
      }, 
      nowPlaying: {
        artist_name : 'Not Checked',
        song_name: 'Not Checked',
        image: ''
      }
    }
    console.log("Room Id" + this.state.roomId);

All I want is to separate this url in the constructor and assign the xPOgk21523aqPW code to roomId as state. How can I do that?

The easiest way would be using react-router-dom with dynamic path:

<Switch><Route path="/room/:id" children={} /></Switch>

then you'll be able to access the id by using the UseParams hook:

const { id } = useParams();

Docs: https://reactrouter.com/web/example/url-params

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM