简体   繁体   English

react-router-dom 只更改 url

[英]react-router-dom changes only url

I've made a website with a router-dom and unfortunately URL changes and I need to refresh the page to see right component.我制作了一个带有路由器 dom 的网站,不幸的是 URL 发生了变化,我需要刷新页面才能看到正确的组件。

I've already seen all the threads on StackOverflow and none of them helped me.我已经看过 StackOverflow 上的所有线程,但没有一个对我有帮助。

So, I have App.js as the main container:所以,我有 App.js 作为主容器:

<div>
  <Header />
  <Router>
    <Switch>
      <Route exact path="/" component={Index} />
      <Route path="/offer" component={Offer} />
    </Switch>
  </Router>
</div>

In header I have links:在标题中,我有链接:

<Router>
  <Link to="/">Start</Link>
  <Link to="/offer">Offer</Link>
</Router>

To App.js I import Router, Switch, and Route.对于 App.js,我导入了 Router、Switch 和 Route。 To header.js I import Router and Link.到 header.js 我导入路由器和链接。

Everything is displayed by standard ReactDOM.render(, document.getElementById('root'));一切都由标准 ReactDOM.render(, document.getElementById('root')) 显示;

Could you help me out, please?请你帮我一下好吗?

You should only have one Router component, preferably as the topmost component of your app.您应该只有一个Router组件,最好是作为应用程序的最顶层组件。

Example例子

function Header() {
  return (
    <div>
      <Link to="/">Start</Link>
      <Link to="/offer">Offer</Link>
    </div>
  );
}

function App() {
  return (
    <Router>
      <div>
        <Header />
        <Switch>
          <Route exact path="/" component={Index} />
          <Route path="/offer" component={Offer} />
        </Switch>
      </div>
    </Router>
  );
}

It's because Header is not inside the Router:这是因为 Header 不在路由器内部:

Try this:尝试这个:

<Router>
  <Header />
  <Switch>
    <Route exact path="/" component={Index} />
    <Route path="/offer" component={Offer} />
  </Switch>
</Router>

In Header component :在 Header 组件中:

<div>
  <Link to="/">Start</Link>
  <Link to="/offer">Offer</Link>
<div>

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

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