无法从React Router 4嵌套路由中的Redux Connect()获取道具

时间:2017-07-28 08:33:03

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

我试图在我的嵌套路由中从Redux connect()访问道具。但是不能让它发挥作用..

我有以下组件:

main.js     const initState = {};

const history = createBrowserHistory();
const store = configureStore(initState, history);

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

在app.js中我设置了几条路线

class App extends Component {
  render() {
    return (
      <Switch>
        <Route path="/auth" component={Auth} />
        <Route exact path="/" component={Home} />
      </Switch>
    );
  }
}

export default withRouter(App);

然后在Auth组件

function Auth(props) {
  return (
    <div>
      <Route exact path={`${props.match.path}/login`} component={Login} />
    </div>
  );
}
export default withRouter(Auth);

最后我的登录组件

export class Login extends Component {
  login({email, password}) {
    this.props.login({ email, password });
  }

  render() {
    return (
      <Form
        onSubmit={(credentials) => this.login(credentials)} />
    );
  }
}

Login.propTypes = {
  login: PropTypes.func
}

const mapDispatchToProps = (dispatch) => {
  return {
    login: (credentials) => dispatch(loginRequest(credentials))
  };
}

export default connect(null, mapDispatchToProps)(Login);

触发this.props.login({ email, password });应该发送我的loginRequest(credentials)行动。

但是我收到this.props.login is not a function错误。实际上我的登录组件中没有设置任何道具。connect()似乎根本没有效果。

父母可以访问由connect()注入的道具,但是这条二级路线无法获得它应该接收的道具..

我希望它足够清楚......我错过了什么吗?关于什么可能出错的任何想法?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

export定义逻辑类时删除export class Login extends Component {,并确保将逻辑作为默认组件导入,如import Login from '/path/to/Login

class Login extends Component {
  login({email, password}) {
    this.props.login({ email, password });
  }

  render() {
    return (
      <Form
        onSubmit={(credentials) => this.login(credentials)} />
    );
  }
}

Login.propTypes = {
  login: PropTypes.func
}

const mapDispatchToProps = (dispatch) => {
  return {
    login: (credentials) => dispatch(loginRequest(credentials))
  };
}

export default connect(null, mapDispatchToProps)(Login);