React Router v4 with Redux - dispatch未通过

时间:2017-07-01 14:10:27

标签: javascript reactjs typescript react-router

所以,我一直试图将我的应用程序切换到React Router v4(api已经发生了很大变化),这就是我已达到的地方:

路由器设置

const createStoreWithMiddleware = applyMiddleware(
   thunkMiddleware,
   createLogger
)(createStore);
const store = createStoreWithMiddleware(rootReducer);

const RouterLayout = () => (
    <Provider store={store}>
        <App>
            <Switch>
                <Route component={Login} path="/login" />
                <Route component={AccountDetails} path="/account/:id" />
            </Switch>
        </App>
    </Provider>
);

const routes = (
    <HashRouter>
        <RouterLayout />
    </HashRouter>
);

ReactDOM.render(routes, document.getElementById("app-container"));

现在我的问题是,由于某种原因,我无法将redux连接到我的组件:

export class Login extends React.Component<any, any> {
    componentDidMount() {
        console.log(this.props);
        // this.props.dispatch is undefined 
        // I'm getting however router props: 
        // match: Object, location: Object, history: Object, staticContext: undefined)
    }

    render() {
        return (
            <div>
                This is the Login Component
            </div>
        );
    }
}

export default connect((state: AppState): any => {
    return state;
})(Login);

有趣的是,App组件可以连接并可以无问题地访问dispatch,但Login没有问题。我很确定我做错了什么,但我不知道到底是什么。

1 个答案:

答案 0 :(得分:3)

如果this.props.dispatch不可用,则很可能您的组件未连接到redux。

我认为这里的问题是你要导出两次登录,一次作为反应组件,另一次作为连接到redux存储的组件(具有导出默认值)。在存在RouterLayout的文件中,您可能使用大括号导入login,因此此处的Login组件是未连接到redux的组件。

此外,您的createStore看起来不正确。它应如下所示:

const createStoreWithMiddleware = (reducer) => {
  const middlewares = applyMiddleware(
     thunkMiddleware,
     createLogger
  );

  return createStore(
    reducer,
    middlewares
  );
}

const store = createStoreWithMiddleware(rootReducer);