Router rendering the component on the same page rather than rendering in a new page

半腔热情 提交于 2021-02-11 12:05:15

问题


Router is rendering the page on the same page than to generate a new page. What might be the problem? Whenever I click the link Polls , it renders the page only there but the URL is shown as changed in the browser.

Polls.js

import React from 'react';
import {Link} from "react-router-dom";

class Polls extends React.Component{
    render() {
        return(
            <div>
                <h1>Polls Page</h1>
                <p>This is Polls Page </p>
            </div>
        )
    }
}

export {Polls}

Choices.js

import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import {Polls} from "./Polls";

class ShowChoice extends React.Component{
    render() {
        return(
            <Router>
                <Link to='/polls'>Polls</Link>
                <Route path='/polls' component={Polls} />
            </Router>
        )
    }
}

And the ShowChoice is rendered inside APP

flow of rendering is like

index>APP>ShowChoices 

(link to the Polls inside ShowChoices)

and my APP.js is

class App extends React.Component {
    render() {
        return (
            <ShowChoice formResult={this.state.result} />
        );
    }
}
export default App;


回答1:


You have added your Route in ShowChoice component. Your ShowChoice component is then added to App component.

So whenever yo click the Link, your URL will get changed but it will render the component in App component only. So your App component's content is also visible to you.

To make it feel like you get new page when you click the Link, you need to combine all the Route at top level, may be in a separate component,

const Routers = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/polls" component={Polls} />
      </Switch>
    </BrowserRouter>
  )
}

So this will render App component by default on first render, which will render ShowChoice component added in App component and you will see Link for your Polls component.

Now clicking on Link, you will get new page of your Polls component.

Demo




回答2:


Try to change path and use exact like that

<Route exact path="/polls" component={Polls}/>

More info: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Route.md



来源:https://stackoverflow.com/questions/57788712/router-rendering-the-component-on-the-same-page-rather-than-rendering-in-a-new-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!