我有以下应用:
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));
fetchArticles
和searchArticles
是redux操作。
我想处理那个案子:
/
)SearchBoxWithImages
组件处理,我想将网址更改为/search?q=term
(术语是来自onSearch
处理程序的回调)searchArticles
设置redux状态目前只有状态被更改(因为调用searchArticles
操作)。网址未更改,因此SearchPage
容器未被调用。
答案 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
。