无法将参数从 Link 传递到组件

can't get passed param from Link to component

我在主要组件中有这个 Link:

<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.usernamereturnsundefined,以及props.match.params.value或者 props.location...

如何获取组件中传递的参数?.谢谢

因为你的 link 应该导航到 /protected/:username,你需要你的受保护组件也在同一路径上呈现

Link

<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>