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
阅读 12.2k
3 个回答

自问自答吧,国外也很多人问这个问题,这算是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改变查询参数并不会刷新或者说重载组件的问题  

1.感觉楼主的搜索流程有些奇怪,搜索k1,url会转到abc.com/search/beijin/k1,搜索k2,页面不发生跳转,那此时的url显示的不还是abc.com/search/beijin/k1?你这个路由和页面逻辑的对应关系就显得有些混乱。
2.不明白楼主重置state的难点在哪里,假设你state中通过data字段保存查询结果,通过page字段保存当前的查询页面,重置state 的话,只要在搜索k2的结果返回时,setState({data: [], page: 0})就完成了重置,然后再setState({data: newData})。

你想问的应该是搜索了k2为什么一面没有更新吧?

推荐问题