【问题标题】:How to pass props in Link and Route component at the same time?如何在 Link 和 Route 组件中同时传递 props?
【发布时间】:2020-08-05 07:16:41
【问题描述】:

我得到一个一直显示的主要父组件,该组件连接到 api 以获取授权密钥。我只在他内部的组件之间进行路由,并且我需要将来自父组件的授权传递给名为 Playlist 的组件我喜欢这样做:

<Route path="/playlists" component={() => <Playlists authKey={auth} />} />

但我还需要从其他子组件传递道具(播放列表的链接在哪里)我喜欢这样做:

<Link to={{ pathname: '/playlists', myProps: { name: 'some name' }}}

问题在于,在 Playlist 组件的道具中,我只获得了在 Route 组合中传递的数据,但我还需要来自 Link

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您可以在 URL 中包含参数。将您的路径声明为:

    <Route path="/playlists/:name" component={() => <Playlists authKey={auth} />} />
    

    然后将您的链接设置为指向它:

    <Link to={{ pathname: '/playlists/some_name'}} />
    

    然后访问它,使用:

    const name = this.props.match.params.name
    

    【讨论】:

    • 这真的很有帮助,但是现在当我将对象作为状态参数传递时,我得到了未定义
    • 嗯,这很正常,因为在URL中,你只能设置strings/numbers/bools等原始类型。
    • 没错,但是在 URL 中我只传递了 name 参数,其余的对象我作为 state: { key: value } 传递。现在我意识到我还需要设置 searchhash 参数才能访问状态:) 谢谢你的时间
    猜你喜欢
    • 2020-06-12
    • 2017-11-25
    • 1970-01-01
    • 2020-01-09
    • 2019-12-05
    • 2021-09-08
    • 2016-03-19
    • 2020-02-15
    • 1970-01-01
    相关资源
    最近更新 更多