将道具传递给组件,React Router V4

Pass props to a component, React Router V4

我有一个包含此组件树的应用程序:

App
   Header
   Main
     Searcher
     List_of_albums
       Album

所以,我的想法是在主页上有一个相册搜索器,它会在搜索后显示一个相册列表。为此,我正在读取组件 Main 中的 .json 文件,然后将道具传递给 List_of_albums 和 Album.

到目前为止一切正常。

现在我想通过一个按钮访问新路径中每个专辑的信息:/id_of_the_album.

此按钮在组件相册中的本地化如下:

let albumLink = `/${this.props.id}`
<Link to={albumLink}></Link>

为此,我在组件 App 中尝试了这个:

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

class App extends Component {
  constructor(){
  super()
  }

  render () {
   return (
     <Router>
      <Fragment>
       <Header />
        <Switch>
          <Route exact path='/' render={() => {
           return(
             <Main />
            )
          }} />

         <Route path='/:id_of_the_album' render={() => {
           return(
             <Profile />
           )
          }} />
          </Switch>
        </Fragment>
      </Router>
    )
  }
}

其中 Profile 是显示相册详细信息的新组件。 在这个新组件中,我想用这样的东西打开个人相册的 jsons:

import singlejson from '../data/""""herethe_id_of_the_album"""".json'

但是如何将 id_of_the_album 传递给组件配置文件??

这样写:

<Route path='/:id_of_the_album' render={props => <Profile {...props} /> } />

现在在 Profile 组件中,它应该可以通过以下方式使用:

this.props.match.params.id_of_the_album

在 React 路由器中,当您从一个组件路由到另一个组件时,您将拥有一个对象 match,其中包含许多属性。其中之一是 params,它可以帮助我们识别是否有任何参数通过路由传递给子组件。

对于您的情况,您可以在子组件中使用 match.params.id_of_the_album

This link 提供了有关 React 路由器的更多信息。