Redux调度和更改网址

时间:2018-04-10 20:49:41

标签: reactjs redux react-router

我有以下应用:

index.js

const store = createStore(rootReducers, applyMiddleware(createLogger()));

store.dispatch(fetchArticles());

ReactDOM.render(
    <Provider store={store}>
        <Router>
            <Switch>
                <Route exact path='/' component={ArticlesPage}/>
                <Route path='/search' component={SearchPage}/>
            </Switch>
        </Router>
    </Provider>,
    document.getElementById('root')
);

ArticlesPage.js

const ArticlesPage = ({groups, onSearch}) => (
    <Grid>
        <SearchBoxWithImages onSearch={onSearch}/>
        <CategorySections groups={groups}/>
    </Grid>
);

const mapStateToProps = state => ({
    groups: state.articles.groups
});

const mapDispatchToProps = dispatch => ({
    onSearch: (q) => dispatch(searchArticles(q))
});

export default withRouter(connect(
    mapStateToProps,
    mapDispatchToProps
)(ArticlesPage));

fetchArticlessearchArticles是redux操作。

我想处理那个案子:

  • 输入网站(网址/
  • 搜索后,由SearchBoxWithImages组件处理,我想将网址更改为/search?q=term(术语是来自onSearch处理程序的回调)
  • 调用操作searchArticles设置redux状态

目前只有状态被更改(因为调用searchArticles操作)。网址未更改,因此SearchPage容器未被调用。

1 个答案:

答案 0 :(得分:1)

创建一个像这样的历史对象

import createBrowserHistory from 'history/createBrowserHistory';

export default createBrowserHistory({});

将其应用到您的路由器

import React from 'react';
import {Router, Route, Switch} from 'react-router-dom';
import history from '../services/history';

export default class App extends React.Component {

    render() {
        return (
            <div>
                <Router history={history}>
                    {mainSwitch}
                </Router>
            </div>
        );
    }
}

无论您想以何种方式更改路线,请执行以下操作

import history from '/path/to/history'

history.push('/path/you/want/to/go/to')

这也可以在redux行动中调用,以便您在行动结束后致电history.push