简体   繁体   English

React - React 路由器 dom

[英]React - React router dom

Today I worked with React and also with react-router-dom.今天我使用 React 和 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.我想使用自己的 class 创建自己的“路线”,但在呈现页面之前我不知道如何获取 id。

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?而且我想知道如何在“ServerRoute”中获得该项目-:id,是否有可能,如果可以,请问如何?

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."根据react-router-dom 文档,“渲染道具 function 可以访问与组件渲染道具相同的所有路由道具(匹配、位置和历史记录)。”

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 .这意味着对于您在Router组件的render方法中的示例,您应该可以通过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"/>
        }}/>
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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