使用TypeScript以编程方式在react-redux应用程序中导航

时间:2017-11-06 17:33:38

标签: reactjs typescript redux react-redux react-router

几个小时我没找到方法或任何好的文档,可以告诉我如何以编程方式导航到任何页面。这是我的用例: 我有一个登录表单,一旦用户成功登录,他们应该导航到帐户页面,所以我试图从我的行为中进行此重定向,这是我的代码(注意:我正在使用打字稿)

/* Router.tsx */
const RouterComponent = () => {
    return (
        <Router>
            <Switch>
                <Route exact path="/" component={LoginForm} />
                {/* <Route exact path="/" component={EmployeeList} /> */}
                <Route path="/account" component={Account} />
            </Switch>
        </Router>
    )
}

/* App.tsx */
render () {
        const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

        return (
            <Provider
                store={store}>
                <Router />
            </Provider>
        )
    }

/* Reducer */
import { routerReducer } from 'react-router-redux';
export default combineReducers({
    auth: AuthReducer,
    account: AccountReducer,
    routing: routerReducer
})

/* Login action */
const loginUserSuccess = (dispatch: any, user: any) => {
    dispatch({
        type: LOGIN_USER_SUCCESS,
        payload: user
    });

    // Here I want to add programmatic navigation 
}

我试图关注此文档:https://github.com/reactjs/react-router-redux,但它使用browserHistory from 'react-router'中没有的react-router

Versions:  
"react-router-dom": "^4.2.2", 
"react-router-redux": "^5.0.0-alpha.8",

1 个答案:

答案 0 :(得分:0)

一种方法是使用react-router-redux

import { push } from 'react-router-redux';
...
dispatch(push(`/account/${user.id}`));

您的App.tsx有一个空的<Router />组件未连接到redux,因为它没有嵌套在<Provider>标记内。

/* App.tsx */
render () {
    const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

    return (
        <Provider
            store={store}>
            <Router>
                <Switch>
                    <Route exact path="/" component={LoginForm} />
                    {/* <Route exact path="/" component={EmployeeList} /> */}
                    <Route path="/account" component={Account} />
                </Switch>
            </Router>                
        </Provider>
    )
}
相关问题