我是React的初学者,试图了解路由。我创建了一个学习项目,并希望呈现三个不同的组件,每个组件具有不同的路径。但是,所有路径都会导致显示App组件。
我试图在多个来源上找到解决方案,但无法找出问题!请看一看。预先感谢。
Root.jsx
import React, { Component } from 'react';
import { Router } from 'react-router';
import { Redirect, Route, Switch } from 'react-router-dom';
import ScreensList from './List';
import ScreensWeather from './Weather';
import App from '../App';
const ScreensRoot = () => (
<Router>
<Switch>
<Route exact path='/' component={App}/>
<Route path="/list" component={ScreensList} />
<Route path="/weather" component={ScreensWeather} />
</Switch>
</Router>
);
export default ScreensRoot;
App.js
import React, {Component} from 'react';
import './App.css';
class App extends React.Component {
render(){
return (
<div>
Hello from App!
</div>
)
}
}
export default App;
List.jsx
import React from 'react';
import List from '../components/List';
const ScreensList = () => (
<div>
<List/>
</div>
);
export default ScreensList;
List.jsx
import React from 'react';
const List = (
<div>Hello from List Component!</div>
);
export default List;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import './screens/Root';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
据我所知,您已经定义了ScreensRoot
组件,但是您没有在任何地方使用它。假设您希望将其作为项目的实际根目录,那么在index.js
中必须使用它而不是App
:
ReactDOM.render(<ScreensRoot/>, document.getElementById('root'));
((请注意,您需要在ScreensRoot
中导入index.js
才能使它起作用)。
1。安装
import { Router } from 'react-router';
使用
import { BrowserRouter as Router } from "react-router-dom";
2.change
const List = (
<div>Hello from List Component!</div>
);
to
const List = () => (
<div>Hello from List Component!</div>
);
3.正如其他提到的>
ReactDOM.render(<ScreensRoot />, rootElement);