我是ReactJS的新手,并从React开始我的第一个应用程序。我一直在观看视频并浏览各种教程,最后设法通过Login搭建了我的第一个ReactRedux应用程序。
我已经使用了ReactTraining网站的AuthWorkflow示例。他们在那里使用了一个PrivateRoute组件来保护受保护的路由。我已经实现了它及其工作。
PrivateRoute
问题: 现在我无法将任何自定义数据或类似用户数据发送到受保护的路由。如何发送?
码
import React from "react"; import { BrowserRouter as Router, Route, Link, Redirect, withRouter } from "react-router-dom"; //////////////////////////////////////////////////////////// // 1. Click the public page // 2. Click the protected page // 3. Log in // 4. Click the back button, note the URL each time const AuthExample = () => ( <Router> <div> <AuthButton /> <ul> <li> <Link to="/public">Public Page</Link> </li> <li> <Link to="/protected">Protected Page</Link> </li> </ul> <Route path="/public" component={Public} /> <Route path="/login" component={Login} /> // Here I want to pass the user data to protected component. <PrivateRoute path="/protected" component={Protected} user={username:'ariful', email:'[email protected]'}/> </div> </Router> ); const fakeAuth = { isAuthenticated: false, authenticate(cb) { this.isAuthenticated = true; setTimeout(cb, 100); // fake async }, signout(cb) { this.isAuthenticated = false; setTimeout(cb, 100); } }; const AuthButton = withRouter( ({ history }) => fakeAuth.isAuthenticated ? ( <p> Welcome!{" "} <button onClick={() => { fakeAuth.signout(() => history.push("/")); }} > Sign out </button> </p> ) : ( <p>You are not logged in.</p> ) ); const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => fakeAuth.isAuthenticated ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location } }} /> ) } /> ); const Public = () => <h3>Public</h3>; // show the username here const Protected = (props) => <h3>Protected Username: {props.user.username}</h3>; class Login extends React.Component { state = { redirectToReferrer: false }; login = () => { fakeAuth.authenticate(() => { this.setState({ redirectToReferrer: true }); }); }; render() { const { from } = this.props.location.state || { from: { pathname: "/" } }; const { redirectToReferrer } = this.state; if (redirectToReferrer) { return <Redirect to={from} />; } return ( <div> <p>You must log in to view the page at {from.pathname}</p> <button onClick={this.login}>Log in</button> </div> ); } } export default AuthExample;
如何将用户对象成功发送到受保护的组件?
您需要将传递给组件的...rest参数传递给PrivateRoute组件,但是并非所有组件都需要对组件做出反应。您可以分解React路由器所需的其他参数
...rest
const PrivateRoute = ({ component: Component, exact, strict, path, ...rest }) => ( <Route exact={exact} strict={strict} path={path} render={props => fakeAuth.isAuthenticated ? ( <Component {...props} {...rest} /> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location } }} /> ) } /> );