我无法使用Link导航,这是我的代码
文件夹结构
components
----App.js
----home
----Home
index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import App from './components/App';
ReactDOM.render(
<App />
,
document.getElementById('root')
);
registerServiceWorker();
App.js
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import Home from './home/Home';
class App extends Component {
render() {
return (
<div className="App">
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<Link to="/home">home</Link>
<Router>
<Route
path={'/home'}
exact={true}
component={Home}
/>
</Router>
</div>
);
}
}
export default App;
Home.js
import React, { Component } from 'react';
class Home extends Component {
render() {
return (
<div className="Home">
Home Page
</div>
);
}
}
export default Home;
没有Link似乎没问题,但是当我直接输入localhost:3000 / home到url地址栏时,主组件仍然没有出现。 我已经尝试过某种方式来更新/重新安装react-router,但没有任何改变。
答案 0 :(得分:0)
您的Link
组件必须位于Router
组件中。您可以重新构建代码,如
class App extends Component {
render() {
return (
<Router>
<div className="App">
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<Link to="/home">home</Link>
<Route
path={'/home'}
exact={true}
component={Home}
/>
</div>
</Router>
);
}
}