简体   繁体   中英

Url not properly redirecting to a specific page in GatsbyJs

My Problem: I was trying to integrate Gatsby with headless WordPress and successfully did so. I made multiple menus dynamically from WordPress and called those menus through GraphQL. Every thing seems to work fine but when I try to redirect from my home page or from any initial page to another page instead of just going to THAT URL, it appends that URL to the current URL and redirects me to 404 page.

As you can See instead of directing me to about-me page it appended to the home url.

My code: MainMenu.js

import React from "react";
import { StaticQuery, graphql,Link } from "gatsby";
import styled from "styled-components";
import Logo from "./Logo";

const MainMenuWrapper = styled.div
`
display:flex;
background-color:#72498C;
`
const MainMenuInner = styled.div
`
max-width:960px;
margin:0 auto;
display:flex;
width:960px;
height:100%;
`

const MenuItem = styled(Link)
`
text-decoration:none;
color: white;
display:block;
padding:15px 20px;
`

const MainMenu=()=>{
    return(
    <StaticQuery 
    query={
         graphql
         `
         {
            allWordpressWpApiMenusMenusItems(filter: {name: {eq: "main menu"}}) {
                edges {
                  node {
                    items {
                      title
                      object_slug
                    }
                    name
                  }
                }
              }
         }
         `   
    }
    render={
        props=>(
            <MainMenuWrapper>
                <MainMenuInner>
                    <Logo/>
                    {props.allWordpressWpApiMenusMenusItems.edges[0].node.items.map(item=>(
                        <MenuItem to={item.object_slug} key={item.title}>
                            {item.title}
                        </MenuItem>
                    ))}
                </MainMenuInner>
            </MainMenuWrapper>
        )
    }/>
    )
};

export default MainMenu;

Gatsby-node.js

 process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' const _ = require(`lodash`) const Promise = require(`bluebird`) const path = require(`path`) const slash = require(`slash`) // Implement the Gatsby API “createPagesâ€. This is // called after the Gatsby bootstrap is finished so you have // access to any information necessary to programmatically // create pages. // Will create pages for WordPress pages (route: /{slug}) // Will create pages for WordPress posts (route: /post/{slug}) exports.createPages = ({ graphql, actions }) => { const { createPage, createRedirect } = actions createRedirect({fromPath:'/', toPath:'/home',redirectInBrowser: true, isPermanent:true}) return new Promise((resolve, reject) => { // The “graphql†function allows us to run arbitrary // queries against the local WordPress graphql schema. Think of // it like the site has a built-in database constructed // from the fetched data that you can run queries against. // ==== PAGES (WORDPRESS NATIVE) ==== graphql( ` { allWordpressPage { edges { node { id slug status template title content template featured_media { source_url } } } } } ` ).then(result => { if (result.errors) { console.log(result.errors) reject(result.errors) } // Create Page pages. const pageTemplate = path.resolve("./src/templates/page.js") const portfolioUnderContentTemplate = path.resolve("./src/templates/portfolioUnderContent.js") // We want to create a detailed page for each // page node. We'll just use the WordPress Slug for the slug. // The Page ID is prefixed with 'PAGE_' _.each(result.data.allWordpressPage.edges, edge => { // Gatsby uses Redux to manage its internal state. // Plugins and sites can use functions like "createPage" // to interact with Gatsby. createPage({ // Each page is required to have a `path` as well // as a template component. The `context` is // optional but is often necessary so the template // can query data specific to each page. path: `/${edge.node.slug}/`, component: slash(edge.node.template === 'portfolio_under_content.php'? portfolioUnderContentTemplate: pageTemplate), context: edge.node, }) }) }) // ==== END PAGES ==== // ==== POSTS (WORDPRESS NATIVE AND ACF) ====.then(() => { graphql( ` { allWordpressPost { edges{ node{ id title slug excerpt content } } } } ` ).then(result => { if (result.errors) { console.log(result.errors) reject(result.errors) } const postTemplate = path.resolve("./src/templates/post.js") // We want to create a detailed page for each // post node. We'll just use the WordPress Slug for the slug. // The Post ID is prefixed with 'POST_' _.each(result.data.allWordpressPost.edges, edge => { createPage({ path: `/post/${edge.node.slug}/`, component: slash(postTemplate), context: edge.node, }) }) resolve() }) }) // ==== END POSTS ==== //==== Portfolio ====.then(() => { graphql( ` { allWordpressWpPortfolio { edges { node { id title slug excerpt content featured_media { source_url } acf { portfolio_url } } } } } ` ).then(result => { if (result.errors) { console.log(result.errors) reject(result.errors) } const portfolioTemplate = path.resolve("./src/templates/portfolio.js") _.each(result.data.allWordpressWpPortfolio.edges, edge => { createPage({ path: `/portfolio/${edge.node.slug}/`, component: slash(portfolioTemplate), context: edge.node, }) }) resolve() }) }) // ==== END Portfolio ==== }) }

Main Menu Query in GraphQL

In MainMenu.js try to replace:

<MenuItem to={item.object_slug} key={item.title}>
   {item.title}
</MenuItem>

by:

<MenuItem to={`/${item.object_slug}`} key={item.title}>
   {item.title}
</MenuItem>

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