[英]React-Router V4 - Passing Props to Render function in Route Component to generate new component
我无法理解如何呈现<Route>
的子组件,该子组件将检查来自父级的prop布尔值以查看状态是否被授权。 我希望能够通过传播使用其他道具来证明它的未来。 有人可以帮我尝试拧开它吗?
这是我要创建的专用路线的代码:
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;
在传递给render
的内联函数中,您可以访问props
因此您可以执行以下操作:
export const PrivateRoute = (props) => (
<Route to={props.path} render={() => {
if(props.authenticated) {
return <Component {...props} />;
}
return <Redirect to="/" />;
}}/>
);
不确定,但是我认为这应该写成
export const PrivateRoute = (props) => (
<Route {...props} render={({...props}) => (
{props.authenticated ? <Component {...props} /> : <Redirect to='/' />
}/>
)
并确保authenticate
通过您的顶级组件。
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> );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.