简体   繁体   English

如何使用 react-router-dom 创建动态路由?

[英]How to create dynamic routes with react-router-dom?

I learn react and know, how to create static routes, but can't figure out with dynamic ones.我学习反应并知道如何创建 static 路线,但无法弄清楚动态路线。 Maybe someone can explain, I'll be very grateful.也许有人可以解释一下,我将不胜感激。 Let there be two components, one for rendering routes, and another as a template of a route.假设有两个组件,一个用于渲染路由,另一个作为路由的模板。 Maybe something wrong in the code, but hope You understand..也许代码有问题,但希望你明白..

Here is the component to render routes:这是渲染路由的组件:

import React, { Component } from 'react';
import axios from 'axios';
import Hero from './Hero';

class Heroes extends Component {
  constructor(props) {
    super(props);
    this.state = {
      heroes: [],
      loading: true,
      error: false,
    };
  }
  componentDidMount() {
    axios.get('http://localhost:5555/heroes')
      .then(res => {
        const heroes = res.data;
        this.setState({ heroes, loading: false });
      })
      .catch(err => { // log request error and prevent access to undefined state
        this.setState({ loading: false, error: true });
        console.error(err);
      })
  }
  render() {
    if (this.state.loading) {
      return (
        <div>
          <p> Loading... </p>
        </div>
      )
    }
    if (this.state.error || !this.state.heroes) {
      return (
        <div>
          <p> An error occured </p>
        </div>
      )
    }
    return (
      <div> 
        <BrowserRouter>
          //what should be here?
        </BrowserRouter>      
      </div>
    );
  }
}

export default Heroes;

The requested JSON looks like this:请求的 JSON 如下所示:

const heroes = [
  {
    "id": 0,
    "name": "John Smith",
    "speciality": "Wizard"
  },
  {
    "id": 1,
    "name": "Crag Hack",
    "speciality": "Viking"
  },
  {
    "id": 2,
    "name": "Silvio",
    "speciality": "Warrior"
  }
];

The route component (maybe there should be props, but how to do it in the right way):路由组件(或许应该有props,但是怎么做对了):

import React, { Component } from 'react';

class Hero extends Component {
  render() {
    return (
      <div>
        //what should be here?
      </div>
    );
  }
}

export default Hero;

I need something like this in browser, and every route url should be differentiaie by it's id (heroes/1, heroes/2...):我在浏览器中需要这样的东西,每条路线 url 应该通过它的 id(英雄/1,英雄/2...)来区分:

John Smith Crag Hack Silvio约翰史密斯峭壁哈克西尔维奥

Each of them:他们每个人:

John Smith.约翰·史密斯。 Wizard.向导。

and so on...等等...

Many thanks for any help!)非常感谢您的帮助!)

  • Use Link to dynamically generate a list of routes.使用Link动态生成路由列表。
  • Use : to indicate url params, :id in the case使用:表示 url 参数, :id在案例中
  • Use the match object passed as props to the rendered route component to access the url params.使用作为道具传递给渲染的路由组件的匹配对象来访问 url 参数。 this.props.match.params.id
<BrowserRouter>
  /* Links */
  {heroes.map(hero => (<Link to={'heroes/' + hero.id} />)}

  /* Component */
  <Route path="heroes/:id" component={Hero} />
</BrowserRouter>

class Hero extends Component {
  render() {
    return (
      <div>
        {this.props.match.params.id}
      </div>
    );
  }
}

To do this you simply add a colon before the url part that should be dynamic.为此,您只需在应该是动态的 url 部分之前添加一个冒号。 Example:例子:

<BrowserRouter>
  /* Dynamic Component */
  <Route path="heroes/:id" component={Hero} />
</BrowserRouter>

Also you can use the useParams hook from react-router-dom to get the dynamic value for use in the page created dynamically: Example:您还可以使用 react-router-dom 中的 useParams 挂钩来获取动态值以在动态创建的页面中使用:示例:

import { useParams } from "react"

const Hero = () => {

    const param = useParams();
    // params.id => dynamic value defined as id in route
    // e.g '/heroes/1234' -> params.id equals 1234

    return (...)
}

Update so this works for React Router v6:更新以便这适用于 React Router v6:

React Router v6 brought some changes to the general syntax: React Router v6 对通用语法进行了一些更改:

Before:   <Route path="heroes/:id" component={Hero} />

Now:      <Route path="heroes/:id" element={<Hero />} />


You can access params like with this.props.match anymore:


Before:   this.props.match.params.id

Now:      import {useParams} from "react-router-dom";
          const {id} = useParams();

You can now just use id as any other variable.

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

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