ReactJS - React Router 未更改组件但 url 正在更改

IT技术 reactjs typescript react-router
2021-04-29 07:42:26

我是 ReactJS 的菜鸟,最近开始学习。我已经使用 TSX 创建了 2 个组件 home 和 ContactList。我正在使用 React-Router 来更改路由。

应用程序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个回答

首先,你需要有一个Router实例

二、MenuLink需要渲染为Router的Child

三、进口Switchreact-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>

        )
    }
}

这是因为您有两个不同的 Router 实例。您只需要一个位于组件层次结构顶部的路由器实例。或者至少……您希望通过 URL 更改的层次结构。

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