反应路由器未呈现正确的组件

时间:2020-01-27 02:07:44

标签: reactjs react-router react-component

我是React的初学者,试图理解路由。我创建了一个学习项目,并希望渲染三个不同的组件,每个组件具有不同的路径。但是,所有路径都会导致显示App组件。

我尝试在多个来源中找到解决方案,但无法找出问题所在!请看一看。预先感谢。

Project Structure

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 个答案:

答案 0 :(得分:3)

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);


Temporary codesandbox

答案 1 :(得分:2)

据我所知,您已经定义了ScreensRoot组件,但是您没有在任何地方使用它。假设您希望将其作为项目的实际根,那么在index.js中必须使用它而不是App

ReactDOM.render(<ScreensRoot/>, document.getElementById('root'));

(请注意,您需要在ScreensRoot中导入index.js才能正常工作。