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

发布于 2021-01-31 22:44:11

我学会了反应,知道如何创建静态路由,但无法弄清楚动态路由。也许有人可以解释,我将不胜感激。假设有两个组件,一个用于渲染路线,另一个作为路线的模板。也许代码有问题,但希望您理解..

这是呈现路线的组件:

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;

请求的JSON如下所示:

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

路线组件(也许应该有道具,但是如何以正确的方式做到):

import React, { Component } from 'react';

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

export default Hero;

我在浏览器中需要这样的东西,并且每个路由URL的ID都应该有所不同(heroes / 1,heroes / 2 …):

约翰·史密斯(John Smith)Crag Hack Silvio

他们每个人:

约翰·史密斯。 向导

等等…

非常感谢您的帮助!)

关注者
0
被浏览
321
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。
    • 使用Link动态生成路由的列表。
    • 使用:指示网址参数,:id在案件
    • 使用作为道具传递给呈现的路由组件的match对象访问url参数。 this.props.match.params.id


      / Links /

      / Component /




知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看