首页 文章

使用时从 React Router 中删除哈希

提问于
浏览
0

我使用以下代码更改我的 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 中得到一个井号#,i.e。 http://localhost:8080/review/request/5066549580791808/yes#

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

但视图不会更新,如果我再次回击,它将返回到以下的根路径:

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

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

有人能告诉我我做错了什么吗?谢谢!

1 回答

  • 0

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

    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。

相关问题