无法从链接传递到组件的参数

时间:2018-07-16 12:45:38

标签: reactjs react-native react-native-router-flux

我在主要组件中有此链接:

<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.valueprops.location ...

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

1 个答案:

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