在ReactJS中将道具传递给props.history.push('path')

时间:2017-08-02 12:31:12

标签: reactjs single-page-application

背景

我试图通过构建我的第一个单页应用程序来学习ReactJS。我通常在.NET MVC中工作,而且我在SPA所需的思考过程中遇到了一些困难。无论如何,我使用的是最新版本的React&反应路由器。这就是我现在所拥有的。

my app UI

CODE

到目前为止,我总共有 5个真正的组件。这里按顺序使用:

  1. 应用
  2. ArtistList
      

    循环播放艺术家数组(到目前为止来自本地变量)并绘制Artistcards

  3. ArtistCard
  4. 艺术家
      

    将此视为艺术家的详细视图。您可以通过单击ArtistCard(屏幕截图中显示)来到此处,以便您可以看到LyricCards列表

  5. LyricCard
  6. 我的路线在我的[应用程序组件]中声明。这是JSX。

    <div className="App">
      <Header />
      <Route exact path="/" render={routeProps => <ArtistList {...routeProps} artists={artists} />} />
      <Route exact path="/artist/:artistUrlName" component={Artist} />
    </div>
    

    以下是我的[ArtistList组件]的代码

    class ArtistList extends Component {
      render() {
        return (
          <div className="artist-list">
            {this.props.artists.map(artist =>
              <ArtistCard key={artist.imageUrl} artist={artist} history={this.props.history} />
            )}
          </div>
        );
      }
    }
    

    以下是我的[ArtistCard组件]的代码

    class ArtistCard extends Component {
      constructor() {
        super();
        this.navigateToArtist = this.navigateToArtist.bind(this);
      }
      navigateToArtist() {
        this.props.history.push(`/artist/${this.props.artist.urlFriendlyName}`);
      }
      render() {
        return (
          <div
            className="artist-card"
            onClick={() => {
              this.navigateToArtist();
            }}
          >
            <div className="artist-image">
              <img src={this.props.artist.imageUrl} alt="artist" />
            </div>
            <div className="artist-name">
              <h3>
                {this.props.artist.name}
              </h3>
            </div>
            <div className="artist-meta">
              <div className="artist-lyrics">
                <h4>
                  {this.props.artist.lyricsCount}
                </h4>
              </div>
              <div className="artist-hearts">
                <h4>
                  {this.props.artist.likesCount}
                </h4>
              </div>
            </div>
          </div>
        );
      }
    }
    

    问题

    当点击艺术家卡片(例如James Brown)时,我能够导航到路线/artist/james-brown,但我不知道如何传递[Artist组件]所需的数据(道具) ](将显示歌词卡列表)。

    如上所述,这是我的第一个SPA,我不确定我是否会采用正确的方法。作为开发人员,我知道我可以从URL中获取urlFriendlyName并将其传递给API端点,该端点将为我提供歌词列表(以及我可能需要的其他内容),然后我可以将其设置为通过一个相关的组件生命周期安装方法,组件的state

    但这是SPA的方式吗?我的意思是我可以做的另一种方法是在我的控制器/父[App组件]中单独调用API端点并获取所有艺术家及其歌词以及我需要的其他所有内容?我仍然需要你告诉我如何通过道具将艺术家数据和所有他/她的歌词传递给[艺术家组件]。

0 个答案:

没有答案