简体   繁体   中英

React route breaking when page gets refreshed

I'm working on a project with the WordPress REST API and ReactJS. In order to make the routing work, I made a custom endpoint to retrieve all the primary navigation pages. Based on these pages, I create new React routes dynamically.

One of these routes is the /blog/ route. This route is the archive page for all the blog articles which will be written. The singlepage of the blog article is located at /blog/:title route. the title in this case is the title of the post.

Based on this title, I make a request to retrieve the information which is required for the singlepage.

The above works almost perfectly, the content is shown at the correct places, and the calls are all successful.

The only problem is, is that when I am viewing a singlepage of a blog article, and I refresh my browser, the url gets changed to /<title of the post>/ . This route is non-existent and therefore doesn't show any content.

Does anyone have any idea how I can prevent this from happening?

Code (If more code is needed, please let me know):

The Router:

<Router>
  <Header
    absolute={this.state.absolute}
    headerColor={this.state.headerColor}
    items={this.state.navItems}
  />
  <Routes
    // Props for the routes component
  />
  <Route
    key='/blog/:title/'
    path='/blog/:title/'
    component={BlogPost}
  />
</Router>

Function which dynamically makes the routes:

makeItems(items) {
  let navItems = []
  items.forEach(item => {
    if (item.children) {
      item.children.forEach(child => {
        let ChildComponent = this.identifyComponent(child)
        let childPathName = new URL(child.url).pathname

        navItems.push(
          <Route
            key={child.id}
            path={`${childPathName}`}
            component={ChildComponent}
          />
        )
      })
    }

    let NavComponent = this.identifyComponent(item)
    let pathName = new URL(item.url).pathname

    if (item.title === "Home") {
      navItems.push(
        <Route
          exact
          key={pathName}
          path={`${pathName}`}
          render={() => (
            <NavComponent
              startHomeSlider={() => this.props.startHomeSlider()}
              stopHomeSlider={() => this.props.stopHomeSlider()}
              slogan={this.props.themeOptions.slogan}
              animation={this.props.animation}
              currentCase={this.props.currentCase}
            />
          )}
        />
      )
    } else {
      navItems.push(
        <Route
          exact
          key={pathName}
          path={`${pathName}`}
          component={NavComponent}
        />
      )
    }
  })

  return navItems
}

.htaccess file:

# BEGIN WordPress
# De richtlijnen (regels) tussen `BEGIN WordPress` and `END WordPress` worden
# dynamisch aangemaakt en zouden enkel aangepast mogen worden via WordPress filters.
# Elke wijziging aan deze richtlijnen tussen deze markeringen worden overschreven.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

I apologize if I am looking at this wrong...but it looks like you are using <Route> where you should be using <Link>.

My WordPress/React App has all of the Routing in App.js...

 function App() { 

  return (
    <div className="app-wrapper page" style={{minHeight: '100vh'}}>
      <Router>
        <Navibar />
        <Switch>
          <Route path="/category/:title" exact component={Posts} />
          <Route path="/category/:title/page=:pageNum" exact component={Posts} />
          <Route path="/tag/:tag" exact component={Posts} />
          <Route path="/archive/:year/:month" exact component={Posts} />
          <Route path="/:post/:id/" exact component={Posts} />
          <Route path="/page=:blogPage" exact component={Posts} />
          <Route path="/:id/" exact component={Page} />
          <Route path="/" exact component={Homepage} />
        </Switch>
        <Footer />
      </Router>
    </div>
  );
}

export default App;

Then I use <Link> to create links to the posts/pages...'to' is the same as 'href'.

<Link key={navItem.ID} to="/post/hello-world/" className="navbar-right nav-link">{navItem.title}</Link>);

Now, you will have the correct url in the browser address bar...and since your Routes are static...will render the page correctly.

When you refresh the page...React will use the same routing and render the page the same as it was before the refresh.

Apparently the thing that was wrong, was the WordPress settings for permalinks. Since the settings said blogs should be at /<title of post> , but my code said it had to be at /blog/<name of post> so whenever I refreshed it would default to WordPress' settings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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