【问题标题】:Remove hash from React Router when using使用时从 React Router 中删除哈希
【发布时间】:2016-10-10 18:32:59
【问题描述】:

我使用以下代码更改我的 React Router 路径:

import React from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import { Router, Route, browserHistory, IndexRoute } from 'react-router'


var currentRouteName = this.props.location.pathname;
const path = currentRouteName + '/yes';
browserHistory.push(path);

路由器如下所示:

ReactDOM.render((
    <Router history={browserHistory}>
        <Route path="/review/request/:id">
            <IndexRoute component={QuestionBox}/>
            <Route path="yes" component={PositiveBox}/>
            <Route path="no" component={NegativeBox}/>
            <Route path="thank-you" component={ThankYouComponent}/>
        </Route>
    </Router>
), document.getElementById('parent-div'))

当我使用上面的代码更改路径时,我的 URL 中会出现一个井号 #,即http://localhost:8080/review/request/5066549580791808/yes#

当我在浏览器中单击返回时,哈希将消失并给我路径:http://localhost:8080/review/request/5066549580791808/yes

但是视图不会更新,如果我再次回击,它会回到根路径:

http://localhost:8080/review/request/5066549580791808

并且视图将再次更改 IndexRoute。我的想法和我希望发生的事情是只需要按一次后退按钮。

谁能告诉我我做错了什么?谢谢!

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    好的,我找到了答案,但有点烦人,在我的 QuestionBox 对象的点击处理程序中是这样的:

    click_like_button() {
            console.log("Like button clicked:", this); // React Component instance
            this.setState({should_hide: true});
            var currentRouteName = this.props.location.pathname;
            const path = currentRouteName + '/yes';
            browserHistory.push(path);
        }
    

    注意到有什么遗漏了吗?我没有传递点击生成的实际事件,所以我将其更改为:

    click_like_button(event) {
            event.preventDefault();
            console.log("Like button clicked:", this); // React Component instance
            this.setState({should_hide: true});
            var currentRouteName = this.props.location.pathname;
            const path = currentRouteName + '/yes';
            browserHistory.push(path);
        }
    

    现在我已经传入了事件,然后我执行了 event.preventDefault();和ta-da它的工作原理!为什么我必须这样做我不确定,更聪明的人无疑会告诉你,但我认为这个问题有点烦人,应该在 react-router 上修复或警告。

    【讨论】:

    • click_like_button 方法是否通过单击具有href='#' 属性的锚点触发?这可能就是为什么它将哈希添加到 URL 中的原因。 event.preventDefault(); 是防止这种情况发生的常用方法。
    • 我同意@FabianSchultz 的观点,您可能只是在href 中使用了#,而没有preventDefault(),默认情况下使用#
    猜你喜欢
    • 2016-05-12
    • 2018-11-17
    • 2011-05-29
    • 2012-04-19
    • 1970-01-01
    • 2019-01-22
    • 2022-09-22
    • 1970-01-01
    相关资源
    最近更新 更多