将React Route传递给子组件

时间:2019-11-21 18:44:25

标签: reactjs

我有路由器功能,可以从其中调用我的Home组件

import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./containers/Home";
import NotFound from "./containers/NotFound";
import InputForm from "./containers/InputForm";
import Logout from "./containers/Logout";

export default function Routes() {
    return (
        <Switch>
            <Route path="/" exact component={Home}/>
            <Route path="/login" render={(props) => <InputForm {...props} buttonName={"Вход"} type={"login"} />}/>
            <Route path="/signup" render={(props) => <InputForm {...props} buttonName={"Регистрация"} type={"signup"} />}/>
            <Route path="/logout" exact component={Logout}/>
            <Route component={NotFound}/>
        </Switch>
    )
}

在我的Home组件中,我已经像这样连接到Redux存储

import React from "react";
import { connect } from "react-redux";
import Promo from "./Promo";
import Profile from "./Profile";

const mapStateToProps = state => {
    return { currentUser: state.currentUser };
};

const HomeConnected =({ currentUser }) => {
    if (currentUser.token === undefined) {
        return(
            <Promo />
        )
    } else {
        return(
            <Profile />
        )
    }

};

const Home = connect(mapStateToProps)(HomeConnected);
export default Home

在我的Promo组件中,我想创建重定向到我的应用程序中这样的位置

import React from "react";
import Jumbotron from "react-bootstrap/lib/Jumbotron";
import Button from "react-bootstrap/lib/Button";

export default class Promo extends React.Component{
    handleRegisterClick = () => {
        this.props.history.push("/signup");
    };

    render() {
        console.log(this)
        return (
            <Jumbotron>
                <p>
                    <Button bsStyle="primary" onClick={this.handleRegisterClick}>Try this</Button>
                </p>
            </Jumbotron>
        );
    }
}

但是点击按钮后出现错误

   5 | 
   6 | export default class Promo extends React.Component{
   7 |     handleRegisterClick = () => {
>  8 |         this.props.history.push("/signup");
   9 |     };
  10 | 
  11 |     render() {

如何将Router传递给子组件?

1 个答案:

答案 0 :(得分:3)

您可以将该子组件包装到withRouter提供的react-router-dom HOC(Wrapper)中。

这提供了对react-router API的访问权限。这意味着您将获得所有的方法和道具。

Jus用withRouter包裹起来。

import { withRouter } from "react-router-dom";

...

class Promo extends React.Component{

}

export default withRouter(Promo)