我正在做这个项目,我需要用React Router创建一些路由。我的项目是:
每个广场都有一个ID 200
和201
,我要点击的每个回合我想去的路线如:http://localhost:3000/user/200
或http://localhost:3000/user/201
以及何时去对于该路线,我希望它出现在body
"User 200"
或"User201"
中,我阅读文档但不明白..
我的APP.JS
:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import './App.css';
import Home from './Home';
const App = () => (
<Router>
<Home/>
</Router>
);
export default App;
&#13;
我的HOME.JS
:
import React from 'react';
import Header from './Header';
import Body from './Body';
import './Home.css';
class Home extends React.Component {
render() {
return ( <
div className = 'home' >
<
Header / >
<
Body / >
<
/div>
)
}
}
export default Home;
&#13;
我的BODY.JS
:
import React from 'react';
import './Body.css';
import axios from 'axios';
import {
Link
} from "react-router-dom";
class Body extends React.Component {
constructor() {
super();
this.state = {
employee: [],
}
}
componentDidMount() {
axios.get('http://127.0.0.1:3004/employee').then(
response => this.setState({
employee: response.data
})
)
}
getName = () => {
const {
employee
} = this.state;
return employee.map(name => < Link className = 'link'
to = '/user' > < div key = {
name.id
}
className = 'item' > < img className = 'img'
src = {
`https://picsum.photos/${name.name}`
} > < /img> <h1 className='name'> {name.name} </h
1 > < /div> </Link > )
}
render() {
return ( <
div className = 'body' > {
this.getName()
} <
/div>
)
}
}
export default Body;
&#13;
有人可以帮我吗??
答案 0 :(得分:2)
首先,您没有正确设置路由器
App.js
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
class App extends React.Component {
render () {
return (
<Router>
<Home>
<Switch>
<Route path='/user/:token' component={Body} />
</Switch>
</Home>
</Router>
)
}
}
Home.js - 现在你将路由器包装在儿童内部
class Home extends React.Component {
render () {
return (<div className='home' >
<Header />
{this.props.children} {/* This line will render router children which will be Body */}
</div>
)
}
}
Body.js
在体内你现在会收到this.props.match.params
我想你会自己弄清楚