简体   繁体   中英

React Router v4 prevent from running parent route component

I'm building an article search with React [15.6.1] and Router [4.1.1] and noticed that when trying to access an article directly the previous component is loaded, even thou it's not the one that's being called

// === Layout ==================
class Layout extends React.Component {

    render() {
        return (
            <Provider store={this.props.store}>
                <HashRouter>
                    <div>
                        <Switch>
                            <Route exact path="/" component={SearchFilter} />
                            <Route path="/article/:guid" component={Article} />
                        </Switch>
                    </div>
                </HashRouter>
            </Provider>
        );
    }

}

// === SearchFilter ==================
class SearchFilter extends React.Component {

    componentDidMount() {
        console.log('SearchFilter Did Mount');
    }

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

}

// === Article ==================
class Article extends React.Component {

    componentDidMount() {
        console.log('Article Did Mount');
    }

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

}

So when going to the root localhost:3000/#/ it prints

// SearchFilter Did Mount

And when I access an article directly like this localhost:3000/#/article/123456 it prints

// SearchFilter Did Mount
// Article Did Mount

So my question is, how can I prevent it from running the previous route? Because I would like to dispatch some actions there that would trigger some ajax calls to the webservice.

Thanks

Try this instead :

<HashRouter basename="/">
    <div>
        <Switch>
            <Route exact path="/search" component={SearchFilter} />
            <Route path="/article/:guid" component={Article} />
        </Switch>
    </div>
</HashRouter>

Edit:

在此处输入图片说明

For me its working well... So like said... there is something really weird and hidden happening on your machine, or you just put / and then rewrite url to /#/article/123 and it cause the first log stays in the console, but its from the previsous url "/" and if you reload the browser by F5 on the new url /#/article/123 you will see only the "Article did mount"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM