React Router:更改URL但不呈现组件

时间:2019-07-15 08:52:44

标签: reactjs react-router material-ui

作为React和Material-UI的新手,我对路由问题感到绝望。

单击按钮时,URL会更改-但由于某种原因该组件无法呈现。我已经尝试了StackOverflow此处提供的几乎所有可能的解决方案。什么都没有。也许您能找到问题?

这是我的代码:

import React from 'react'

import { Button } from '@material-ui/core'
import { BrowserRouter } from 'react-router-dom'
import { Link, LinkProps } from 'react-router-dom'

const Spielwiese = React.forwardRef<HTMLAnchorElement, LinkProps>(
  (props, ref) => <Link innerRef={ref as any} {...props} />
)

const Favoriten = React.forwardRef<HTMLAnchorElement, LinkProps>(
  (props, ref) => <Link innerRef={ref as any} {...props} />
)

const LandingPage = () => {
  const classes = useStyles()

  return (
    <div className="App">
      <BrowserRouter>
        <Button
          component={Spielwiese}
          to="/spielwiese"
        >
          Dinge finden!
        </Button>
        <Button
          component={Favoriten}
          to="/favoriten"
        >
          Meine Favoriten!
        </Button>
      </BrowserRouter>
    </div>
  )
}

export default LandingPage

非常感谢!

2 个答案:

答案 0 :(得分:1)

您必须为Routes中的每个组件定义BrowserRouter。否则,您将无法浏览您的应用。

请参阅沙盒以获取解决方案:https://codesandbox.io/s/unruffled-flower-to9jd

此外,您应该将LandingPage内容分成其自己的组件。然后,您还将为该组件定义一个Route

App.js

import React from "react";
import ReactDOM from "react-dom";

import { BrowserRouter, Route } from "react-router-dom";
import LandingPage from "./LandingPage";
import Spielwiese from "./Spielwiese";
import Favoriten from "./Favoriten";

const App = () => {
  return (
    <div className="App">
      <BrowserRouter>
        <Route component={LandingPage} path="/" exact />
        <Route component={Spielwiese} path="/spielwiese" />
        <Route component={Favoriten} path="/favoriten" />
      </BrowserRouter>
    </div>
  );
};

export default LandingPage;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

LandingPage.js

import React from "react";
import { Button } from "@material-ui/core";
import { Link } from "react-router-dom";

const LandingPage = () => {
  return (
    <div className="App">
      <Link to="/spielwiese">
        <Button>Dinge finden!</Button>
      </Link>
      <Link to="/favoriten">
        <Button>Meine Favoriten!</Button>
      </Link>
    </div>
  );
};

export default LandingPage;

答案 1 :(得分:0)

好吧,我看不到Spielwiese和Favoriten之间的差异,可能是原因:)?