在链接路径中使用“#”的React-router-dom无法导航到组件

时间:2019-07-14 08:51:50

标签: javascript reactjs react-router-dom

我正在尝试创建一个功能,当用户单击<Link>时,他们导航到另一个组件(“发布”)并直接滚动到“注释”。该路径满足<Route>定义的要求,但是当我在URL中使用“#”时,重定向不会生效:

路线:<Route path="/post/:id/:hash" component={Post} />

URL:https://b881s.codesandbox.io/post/4/#ve33e

但是,有趣的是,当我使用“ @”而不是“#”时,该功能可以按预期工作。

URL:https://b881s.codesandbox.io/post/4/@ve33e

我试图找到提到“#”是react-router-dom的某种特殊字符,但是没有发现任何东西。也许我根本就缺少这里的东西?

这是工作代码为https://codesandbox.io/s/scrollintoview-with-refs-and-redux-b881s的沙盒

App.js

import React from "react";
import ReactDOM from "react-dom";
import Home from "./Home";
import Posts from "./Posts";
import Post from "./Post";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import store from "./store";
import { Provider } from "react-redux";

import "./styles.css";

const App = () => {
  return (
    <Provider store={store}>
      <BrowserRouter>
        <div>
          <Switch>
            <Route path="/" exact component={Home} />
            <Route path="/posts" component={Posts} />
            <Route path="/post/:id/:hash" component={Post} />
            <Route path="/post/:id/" component={Post} />
          </Switch>
        </div>
      </BrowserRouter>
    </Provider>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Posts.js

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

class Posts extends React.Component {
  createPostList = () => {
    const { posts } = this.props;

    if (posts.posts) {
      return posts.posts.map(post => {
        return (
          <div key={post.id} className="post">
            <Link to={`/post/${post.id}`}>{post.title}</Link>
            <p>{post.text}</p>
            <div>
              {post.comments.map(comment => {
                return (
                  <div>
                    <Link to={`/post/${post.id}/@${[comment.id]}`}>
                      {comment.id}
                    </Link>
                  </div>
                );
              })}
            </div>
          </div>
        );
      });
    } else {
      return <h4>Loading...</h4>;
    }
  };

  render() {
    return <div>{this.createPostList()}</div>;
  }
}

const mapStateToProps = state => {
  return {
    posts: state.posts
  };
};

export default connect(mapStateToProps)(Posts);

2 个答案:

答案 0 :(得分:1)

URL字符串中#之后的任何内容都称为hash。您可以使用location访问给定location.hash的哈希。因此,在您的路线中,您无需提及:hash。您应该改为通过由Route组件注入到组件中的location对象读取哈希。

您的路线:

<Route path="/post/:id" component={Post} />

要读取Post组件中的哈希:

class Post extends React.Component {
    render() {
        const {location} = this.props;
        console.log(location.hash);
        ...
    }
}

答案 1 :(得分:0)

使用%23作为哈希符号,一定要解决它。

有关它的更多信息:https://en.wikipedia.org/wiki/Percent-encoding

这是您的一个分支,我用%23代表#

https://codesandbox.io/s/scrollintoview-with-refs-and-redux-z8pz8