简体   繁体   中英

React - React router dom

Today I worked with React and also with react-router-dom. I wanted to create my own "Route" using my own class, but I can't figure out how to get the id before rendering the page.

My code is as follows:

import React from "react"
import { Route, Redirect } from "react-router-dom"
import { useAuth } from "../contexts/AuthContext"

export default function ServerRoute({ component: Component, ...rest }) {

    const { currentUser } = useAuth();

    return(
        <Route {...rest} render={props => {
            return currentUser ? /* Do stuff */ <Component {...props}/> : <Redirect to="/auth/login"/>
        }}/>
    )

}

My index is as follows:

import { BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import { AuthProvider } from '../contexts/AuthContext';
import ServerRoute from './ServerRoute';

const TruRouter = () => {

    return(
        <AuthProvider>
            <Router>
                <Switch>
                    <ServerRoute path="/server/:id" component={Component}/>
                </Switch>
            </Router>
        </AuthProvider>
    )

}

export default TruRouter;

And I wonder how I get the item in the "ServerRoute" -:id, is it somehow possible, if so, how please?

Thanks you very much, Domi

According to the react-router-dom documentation , "The render prop function has access to all the same route props (match, location and history) as the component render prop."

This means that for your example in the render method of the Router component, you should have access to the params through props.match.params .

For your case:

// rest of the code above

    return(
        <Route {...rest} render={props => {
            const id = props.match.params.id // get the current route id

            return currentUser ? /* Do stuff */ <Component {...props}/> : <Redirect to="/auth/login"/>
        }}/>
    )

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