简体   繁体   English

React Router 未呈现正确的组件

[英]React Router not rendering correct component

I am a beginner in React and trying to understand routing.我是 React 的初学者并试图了解路由。 I have created a learning project and want to render three different components each with a different path.我创建了一个学习项目,想要渲染三个不同的组件,每个组件都有不同的路径。 However, all the paths result in the display of the App component.但是,所有路径都会导致 App 组件的显示。

I've tried finding solutions on multiple sources, but not able to figure out the issue!我尝试在多个来源上寻找解决方案,但无法找出问题所在! Please have a look.请看一看。 Thanks in advance.提前致谢。

项目结构

Root.jsx根.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应用程序.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列表.jsx

import React from 'react';
import List from '../components/List';

const ScreensList = () => (
    <div>
        <List/>
    </div>
);

export default ScreensList;

List.jsx列表.jsx

import React from 'react';

const List = (
    <div>Hello from List Component!</div>
);

export default List;

index.js索引.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();

1.Insted of 1.Insted

import { Router } from 'react-router';

use

import { BrowserRouter as Router } from "react-router-dom";


2.change 2.改变

const List =  (
  <div>Hello from List Component!</div>
);

to

const List = () => (
  <div>Hello from List Component!</div>
);


3. As others mentioned 3.正如其他人提到的

ReactDOM.render(<ScreensRoot />, rootElement);


Temporary codesandbox临时代码和盒子

As far as I can see, you've defined a ScreensRoot component but you're not using anywhere.据我所知,您已经定义了一个ScreensRoot组件,但您没有在任何地方使用。 Assuming you want that to be the actual root of your project, then in your index.js you must use it instead of App :假设您希望它成为项目的实际根目录,那么在您的index.js您必须使用它而不是App

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

(Note that you'll need to import ScreensRoot in your index.js in order for this to work). (请注意,您需要在index.js中导入ScreensRoot才能使其工作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM