ReactJS-React Router不会更改组件,但网址会更改

时间:2019-02-07 07:39:24

标签: reactjs typescript react-router

我是ReactJS的新手,最近开始学习。我使用TSX创建了2个组件home和ContactList。我正在使用React-Router更改路线。

App.JS

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import { Header } from "./Grid/header";
import { Footer } from "./Grid/footer";
import { Menulink } from './Grid/Menulinks';
import { Home } from './Grid/Home';
import { ContactList } from './Grid/ContactList';

class App extends Component {
  render() {
    return (
      <div>
        <Header title="This is Header">
        </Header>
        <Menulink></Menulink>
        <Router>
          <switch>
            <Route exact path="/" component={Home} />
            <Route path="/contact" component={ContactList} />
          </switch>
        </Router>
        <Footer></Footer>
      </div>
    )
  }
}

export default App;

Menulink.tsx:

import * as React from 'react';
import { Link, BrowserRouter as Router } from "react-router-dom";

export class Menulink extends React.Component {
    render() {
        return (
            <Router>
                <switch>
                    <Link to="/">Home </Link> |
                    <Link to="/contact">Contact List</Link>
                </switch>
            </Router>

        )
    }
}
  

问题是,当我单击链接时,URL更改了,但是组件没有   得到替换。是因为我写了链接并将两者都路由到   不同的文件?

2 个答案:

答案 0 :(得分:3)

首先,您需要拥有一个Router实例

第二,MenuLink需要呈现为路由器的子级

第三,从Switch导入react-router-dom

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";

import { Header } from "./Grid/header";
import { Footer } from "./Grid/footer";
import { Menulink } from './Grid/Menulinks';
import { Home } from './Grid/Home';
import { ContactList } from './Grid/ContactList';



class App extends Component {
  render() {
    return (
      <div>
        <Header title="This is Header">
        </Header>
        <Router>
          <Route component={Menulink} />
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/contact" component={ContactList} />
          </Switch>
        </Router>
        <Footer></Footer>
      </div>
    )
  }
}

export default App;

import * as React from 'react';
import { Link, BrowserRouter as Router } from "react-router-dom";

export class Menulink extends React.Component {
    render() {
        return (
            <React.Fragment>
                    <Link to="/">Home </Link> |
                    <Link to="/contact">Contact List</Link>
            </React.Fragment>

        )
    }
}

答案 1 :(得分:1)

这是因为您有两个不同的路由器实例。组件层次结构的顶部仅需要一个路由器实例。或至少..您希望随着URL改变的层次结构。

因此,如果将<MenuLink />放在定义路由的<Router>下,则路由将正常工作。