react.js - react-router v4 URL参数改变不重新mount该页面

查看:167
本文介绍了react.js - react-router v4 URL参数改变不重新mount该页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

react-router v4 做查询的功能的时候,地址为abc.com/search/beijin,搜索框输入k1,回车,然后页面跳转到搜索结果页abc.com/search/beijin/k1,这个页面有下拉加载更多功能,下拉,会加载page1,page2。。。page的页码存在state中。
然后搜索结果页头部也有搜索框,如果在这里的搜索框输入,k2,回车,页面不会发生跳转,而且k1的结果数据还是在那里。
有什么办法可以重置state吗?或者有什么办法可以无刷新重载这一页呢?

路由:

<Route path="/search/:category/:keywords?" component={AsyncSearch} />

访问地址

http://0.0.0.0:8888/#/search/all/000
然后再访问
http://0.0.0.0:8888/#/search/all/111

解决方案

自问自答吧,国外也很多人问这个问题,这算是react-router的缺陷吧,很多人用了比较恶心的类似hack的手法解决该问题,各种乱七八糟甚至误导性的答案。
我选择了一个很简洁的hack手法:

跳转部分

// https://github.com/ReactTraining/react-router/issues/1982  解决人:PFight
// 解决react-router v4改变查询参数并不会刷新或者说重载组件的问题
        this.props.history.push('/empty');
        setTimeout(() => {
            this.props.history.replace('/search/' + category + '/' + encodeURIComponent(keywords));
        });

路由部分

render() {
    return (
        <Router history={history}>
            <App>
                <Switch>
                    <Route path="/" exact component={AsyncHome} />
                    <Route path="/city" component={AsyncCity} />
                    <Route path="/search/:category/:keywords?" component={AsyncSearch} />
                    <Route path="/detail/:id" component={AsyncDetail} />
                    <Route path="/user" component={AsyncUser} />
                    <Route path="/empty" component={null} key="empty" />
                    <Route component={AsyncNotFound} />
                </Switch>
            </App>
        </Router>
    );
    // 说明
    // empty Route
    // https://github.com/ReactTraining/react-router/issues/1982  解决人:PFight
    // 解决react-router v4改变查询参数并不会刷新或者说重载组件的问题  

这篇关于react.js - react-router v4 URL参数改变不重新mount该页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆