首页 > 解决方案 > 从 react-router-dom url 中删除哈希

问题描述

我正在使用 react-router-dom v5,有时我会在我的 url 中获得一个哈希值,主要是在刷新页面之后,但有时在单击链接时也会出现,http://localhost:1234/#/或者http://localhost:1234/bags#/如何防止哈希值出现在我的 url 中?

import { BrowserRouter as Router, Route, Switch, browserHistory  } from 'react-router-dom'

class Main extends React.Component {

  render() {
    const {alert, categories, language, products, showAlert, subCategories} = this.props
    return(
      <Router history={browserHistory}>
        <Wrap>
        <Header e={e} p={p} categories={categories} subCategories={subCategories} language={language} />
        <div id="snipcart" data-api-key={process.env.API_KEY}></div>
          <Route style={{ flex: 1 }} render={({ location }) =>
            <TransitionGroup>
              <CSSTransition
                key={location.key}
                timeout={500}
                classNames="page"
                mountOnEnter={true}
                unmountOnExit={true}
              >
                <MainWrap>
                  <Switch location={location}>
                    <Route exact path="/" render={props =>
                      <Home e={e} p={p}
                        categories={categories}
                        subCategories={subCategories}
                        products={products}
                        language={language}
                        {...props} />}
                      />
                    <Route exact path="/delivery" component={Delivery}/>
                    <Route exact path="/terms" component={Terms}/>
                    <Route exact path="/privacy" component={Privacy}/>
                    <Route exact path="/about" component={About}/>
                    <Route exact path="/bags" render={props => <ProductsList  e={e} p={p} categories={categories} subCategories={subCategories} products={products} showAlert={showAlert} language={language} {...props} />} />
                    <Route exact path="/:catId/:productId" render={props => <Product categories={categories} subCategories={subCategories} products={products} showAlert={showAlert} language={language} {...props} />} />
                    <Route component={NotFound} />
                  </Switch>
                </MainWrap>
              </CSSTransition>
            </TransitionGroup>
          } />
 <Query query={CATEGORIES_QUERY}>
        {({ loading, error, data }) => {
          if (loading) return <div>Fetching</div>
          if (error) return <div>Error</div>
          const res = data.categories
          this.props.fetchCategories(res)
          return (
            null
          //   <div>
          //  {res.map(res => res.name)}

          //   </div>
          )
        }}
      </Query>
      <Query query={PRODUCTS_QUERY}>
        {({ loading, error, data }) => {
          if (loading) return <div>Fetching</div>
          if (error) return <div>Error</div>
          const res = data.products
          this.props.fetchProducts(res)
          return (
            null
          //   <div>
          //  {res.map(res => res.name)}

          //   </div>
          )
        }}
      </Query>
          <Footer />
        </Wrap>
      </Router>
    )
  }
}

导航.js

import React from 'react'
import styled from 'styled-components'
import { NavLink } from 'react-router-dom'
import Container from '../../atoms/Container'
import media from '../../atoms/Media'
import * as palette from '../../atoms/Variables'
import Img from '../../atoms/Img'
import Alert from '../../atoms/Alert'
import {
  withRouter
} from 'react-router-dom'

const ShowDesktop = styled.div`
  display: none;
  ${media.lg`
    display: flex;
    width: 100%;
    height: 50px;
  `}
`

const ShowMobile = styled.div`
  display: flex;
  width: 100%;
  height: 50px;
  ${media.lg`
    display: none;
  `}
`

const Wrap = styled.div`
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
`

const Cell = styled(NavLink)`
  display: flex;
  flex: 0 0 25%;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  text-transform: capitalize;
  font-family: 'Teko', sans-serif;
  font-size: 20px;
  color: ${palette.green};
  border-bottom: 3px solid transparent;
  margin-top: 6px 0 3px 0;
  &:nth-child(4) {
    border-right: 0px solid ${palette.green};
  }
  ${media.lg`
    font-size: 24px;
    flex: 0 0 auto;
    padding: 10px;
  `}
`

const InnerCell = styled.div`
  border-bottom: 1px solid ${palette.green};
  padding: 10px;
  text-align: center;
  justify-content: center;
`

class Navigation extends React.Component {

  // componentDidUpdate() {
  //   this.props.e && this.props.history.push('/dashboard')
  // }

  handleHideAlert() {
    setTimeout(() => {
      this.props.hideAlert()
    }, 1000)
  }

  render() {
    const { alert, categories, e, p, } = this.props
    return (
      <Wrap>
        <ShowMobile>

          {categories && categories.map(category =>
          <Cell
            exact
            key={category.id}
            to={e ? `/${category.slug}` : `/${category.slugP}`}
            activeStyle={{ borderBottom: `3px solid #fff`, marginTop: `6px 0 0 0` }}
          >
            {e && category.name}
            {p && category.nameP}
          </Cell>
          )}
          {alert && <div><Alert />{this.handleHideAlert()}</div>}
        </ShowMobile>
        <ShowDesktop>

        {categories && categories.map(category =>
        <Cell
          exact
          key={category.id}
          to={e ? `/${category.slug}` : `/${category.slugP}`}
          activeStyle={{ borderBottom: `3px solid #fff`, marginTop: `6px 0 0 0` }}
        >
          {e && category.name}
          {p && category.nameP}

        </Cell>
        )}
          {alert && <div><Alert />{this.handleHideAlert()}</div>}
        </ShowDesktop>

      </Wrap>
    )
  }
}

export default withRouter(Navigation)

标签: reactjsreact-router-dom

解决方案


您应该删除别名为history的组件中的道具,将其更改如下:<Router />BrowserRouter

<Router>
...
</Router> 

推荐阅读