Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

javascript - React - URL gets updated but the page is not rendered

I am following along a beginner's course on React. The Nav. Bar has two options - About, HomePage. On clicking on the bar, the url gets updated but the page remains the same and nav stays. I get no error.

App.js

import React from 'react';
import HomePage from './HomePage';
import About from './About';
import Header from './common/Header';

function App() {
    function getPage() {
        const route = window.location.pathname;
        if (route === "about") return <About />;
        console.log("hi");
        return <HomePage />;   
        }  
    return(
        <div className="container-fluid">
            <Header>
            { getPage() }
            </Header>      
        </div>
    );
    
}
export default App;

Header.js

import React from 'react';
//to navigate across the website
function Header(){
    return (
        <nav>
            <a href="/"> Home </a> | <a href="/about"> About </a>
        </nav>
    );
}
export default Header;

index.js

import "bootstrap/dist/css/bootstrap.min.css";
import React from "react";
import {render} from "react-dom";
import App from "./components/App";
render(<App />, document.getElementById("root")); 

About.js

import React from 'react';
class About extends React.Component{
    render (){
        return(
            <>
                <h1> About </h1>
                <p> This is the About Page </p>
            </>
        );
    }
}    
export default About;

HomePage.js

import React from "react";
import 'bootstrap/dist/css/bootstrap.min.css';
function HomePage(){
    return(
    <div className="jumbotron">
        <h1>
            Welcome
        </h1>
        <p>
            This is my first React Project
        </p>
        
    </div>
    );
    
}
export default HomePage;

There is no change in the page, only the URL gets updated.

I have tried many solutions on SO but none worked so far.

question from:https://stackoverflow.com/questions/65938616/react-url-gets-updated-but-the-page-is-not-rendered

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm guessing it always displays the <HomePage /> component?

That's because window.location.pathname returns a path with a leading slash. So route === "about" will always be false. You need to check route === "/about" instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...