React Router 无法渲染正确的组件
2020-01-27
147
我是 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();
2个回答
1. 替换
import { Router } from 'react-router';
使用
import { BrowserRouter as Router } from "react-router-dom";
2. 更改
const List = (
<div>Hello from List Component!</div>
);
为
const List = () => (
<div>Hello from List Component!</div>
);
3. 如其他人所述
ReactDOM.render(<ScreensRoot />, rootElement);
Alex
2020-01-27
据我所知,您已定义
ScreensRoot
组件,但未在任何地方使用。假设您希望将其作为项目的实际根,则在
index.js
中,您必须使用它而不是
App
:
ReactDOM.render(<ScreensRoot/>, document.getElementById('root'));
(请注意,您需要在
index.js
中导入
ScreensRoot
才能使其正常工作)。
Ismael Padilla
2020-01-27