首页 > 解决方案 > 在私有路由 React 中传递道具

问题描述

我正在尝试在私人路线中传递几个道具。写这个的正确方法是什么,我错过了什么?这是我的代码。我的应用程序使用此代码,因为用户能够登录并查看仪表板。但是,道具并没有通过。有没有办法将道具传递到私人路线?

   <PrivateRoute exact path="/dashboard" component={Dashboard} render={routeProps =>
            <Dashboard
            handleUpdate={this.handleUpdate}
            book={this.state.book}
            info={this.state.info}
            {...routeProps} />}
          />

仪表板组件

class Dashboard extends Component {

    state = {
        book: this.props.book,
        info: this.props.info, 
        error: '',
    }

    onLogoutClick = e => {
        e.preventDefault();
        this.props.logoutUser();
    };

    render() {
    
    console.log(`BOOK STATE IN DB: ${this.state.book}`)
        
    const { user } = this.props.auth;
    return(
            <div>
                <h4>
                    <b>This is your page</b> {user.name}
                </h4>
                <button onClick={this.onLogoutClick}>Logout</button>
                <h2>Search Book</h2>
                <Search 
                    handleUpdate={this.props.handleUpdate}
                />
                <h4>Book Results</h4>
                <div>{this.state.book}</div>
            </div>
        );
    }
}

Dashboard.propTypes = {
    logoutUser: PropTypes.func.isRequired,
    auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    auth: state.auth
});

export default connect(
    mapStateToProps,
    { logoutUser }
)(Dashboard);

私人路线

import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";

const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  console.log(auth),

  <Route
  {...rest}
  render={props =>
    auth.isAuthenticated === false  ? (
      <Redirect to="/login" />
      
    ) : (
      <Component {...props} />
    )
  }
/>
);
PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
  auth: state.auth
});


export default connect(mapStateToProps)(PrivateRoute);         

标签: javascriptreactjsreact-routerreact-propsmern

解决方案


你能告诉我们 PrivateRouter 组件的代码吗?你可以按照这样的方式

<PrivateRoute exact path="/dashboard" component={Dashboard} props = {{book: this.state.book etc}}/>

并在 PrivateRoute 组件上接收此道具以将其放入子组件


推荐阅读