我学会了反应,知道如何创建静态路由,但无法弄清楚动态路由。也许有人可以解释,我将不胜感激。假设有两个组件,一个用于渲染路线,另一个作为路线的模板。也许代码有问题,但希望您理解..
这是呈现路线的组件:
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
他们每个人:
约翰·史密斯。 向导
等等…
非常感谢您的帮助!)
Link
:
:id
使用作为道具传递给呈现的路由组件的match对象访问url参数。 this.props.match.params.id
this.props.match.params.id
/ Links /
/ Component /
class Hero extends Component { render() { return (