我在主要组件中有此链接:
<Link
to={'/protected/'+this.state.username }
//params={{ username: this.state.user }}
style={styles.navItem_login}
underlayColor="#f0f4f7">
<Text style={styles.navItem_login_text}>Protected Page</Text>
</Link>
然后在App.js中是路由:
<PrivateRoute path="/protected" component={Protected} />
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
const Protected = () => <Text style={styles.header}>{this.props.username}</Text>
但是this.props.username
返回undefined
以及props.match.params.value
或
props.location
...
如何获取组件中传递的参数?谢谢
答案 0 :(得分:1)
由于您的链接应该导航到/protected/:username
,因此您需要在相同的路径上渲染受保护的组件
链接
<Link
to={'/protected/'+this.state.username }
//params={{ username: this.state.user }}
style={styles.navItem_login}
underlayColor="#f0f4f7">
<Text style={styles.navItem_login_text}>Protected Page</Text>
</Link>
App.js
<PrivateRoute path="/protected/:username" component={Protected} />
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
此外,由于Protect
是功能组件,因此您需要访问诸如以下的道具
const Protected = (props) => <Text style={styles.header}>{props.match.params.username}</Text>