我无法理解如何渲染<Route>
的子组件,它将检查来自父级的prop boolean以查看状态是否已被授权。我希望能够通过传播将其他道具传递给未来证明它。有人可以帮我试试这个吗?
以下是我要创建的私人路线的代码:
import React, { Component } from 'react';
import { Route, Redirect } from 'react-router-dom';
import { app } from '../Base'
export const PrivateRoute = (props) => (
<Route {...props} render={(props.authenticated) => (
{props.authenticated} === true
? <Component {...props} />
: <Redirect to='/' />
)}/>
)
和我的App.js
class App extends Component {
constructor () {
super();
this.state = {
authenticated: false,
loading: true
};
}
componentWillMount() {
this.removeAuthListener = app.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({
authenticated: true,
loading: false
})
} else {
this.setState({
authenticated: false,
loading: false
})
}
})
}
componentWillUnmount () {
this.removeAuthListener();
}
render() {
if (this.state.loading === true){
return (
<div style={{ textAlign: "center", position: "absolute", top: "25%", left: "50%"}}>
<h3>Loading</h3>
</div>
)} else{
return (
<div style= { sectionStyle } className="App">
<div className="Jumbotron">
<Header authenticated={this.state.authenticated}/>
<Switch>
<Route exact path="/" render={() => {
}}component={Jumbo}/>
<Route exact path="/login" component={Login}/>
<Route exact path="/logout" component={Logout}/>
<PrivateRoute path="/dashboard" component={Dashboard} authenticated={this.state.authenticated}/>
<Route component={NotFound}/>
</Switch>
</div>
</div>
)}
}
}
export default App;
答案 0 :(得分:2)
在传递给render
的内嵌功能中,您可以访问props
,这样您就可以执行以下操作:
export const PrivateRoute = (props) => (
<Route to={props.path} render={() => {
if(props.authenticated) {
return <Component {...props} />;
}
return <Redirect to="/" />;
}}/>
);
答案 1 :(得分:1)
不确定,但我认为这应该写成
export const PrivateRoute = (props) => (
<Route {...props} render={({...props}) => (
{props.authenticated ? <Component {...props} /> : <Redirect to='/' />
}/>
)
并确保authenticate
通过您的顶级组件。
答案 2 :(得分:0)
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
(Meteor.userId() ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/',
state: { from: props.location },
}}
/>
))
}
/>
);
export const renderRoutes = () => (
<Router history={browserHistory}>
<div>
<Route exact path="/" component={props => <Dashboard {...props} data={{ main: Promotions }} />} />
<Switch>
<Route path="/coin/:coin/:address" component={props => <Dashboard {...props} data={{ main: Wallet }} />} />
</Switch>
</div>
</Router>
);
&#13;