【问题标题】:React Router pass props when using to [duplicate]使用时反应路由器传递道具[重复]
【发布时间】:2018-08-28 17:29:37
【问题描述】:

当用户单击点击区域时,我试图传递所选的帐户 ID。

<Link to="/account" id={1234}>

但是,在我的 Account 组件上,这个“to”将我们带到:

<Route path="/account" component={Account}/>

我得到了未定义。

export default class Account extends Component {
    constructor(props) {
        super(props);

        alert(props.id);

有没有办法使用链接将道具传递给我的组件?

【问题讨论】:

  • 需要你添加更多代码,这样我才能看到我们应该如何将 id 传递给 Account

标签: reactjs react-router


【解决方案1】:

我认为最好的方法是将您的帐户 ID 定义为路由中的参数,例如

<Route path="/account/:id" component={Account}/>
<Link to='/accounts/123'> Go to Accounts</Link>

并使用props.match.params.id 访问它,但如果您想通过道具发送,请执行以下操作:

<Link to={{ pathname: '/account', state: { id: '123'} }}>Go to Accounts</Link>

在帐户中:

const { id } = props.location.state

【讨论】:

    【解决方案2】:

    要将道具传递给孩子,您可以这样做

    <Route
     path="/new/path"
     render={(routeProps) => (
       <MyComponent {...routeProps} {...props} />
     )}
    />
    

    并且不要跳过展开运算符。

    【讨论】:

      【解决方案3】:

      链接向路由传递信息的一种简洁方法是在 URL 中使用参数:

      // 1. Link to what would be the URL for a specific account.
      // would probably replace `1234` for a variable here
      <Link to={`/account/${1234}`>View Account 1234</Link>
      
      // 2. "capture" the ID in the url using a param matcher
      // We'll receive this param as "props.match.params.id" in the render function
      // using component={} also works here, and the props will be injected directly into the component instead,
      // but render={} here looks cleaner to me, and is more flexible if you wanna pass more props
      <Route path="/account/:id" render={props => <Account id={props.match.params.id} />} />
      

      See the docs for more information on how the render prop works.

      【讨论】:

        猜你喜欢
        • 2020-04-15
        • 2019-08-15
        • 2018-08-22
        • 2022-11-14
        • 2020-07-07
        • 2022-07-28
        • 2020-03-26
        • 2020-11-12
        • 2017-07-12
        相关资源
        最近更新 更多