为什么渲染组件时会出错?

时间:2018-04-28 16:37:19

标签: javascript reactjs components

我试图通过道具将状态呈现给嵌套组件。这就是我App.js中的内容:

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchResults: [
        {name: 'Money Trees',
        artist: 'Kendrick Lamar',
        album: 'Album Title',
        id: '1234'},

        {name: 'Reptilia',
        artist: 'The Stroks',
        album: 'Is This It',
        id: '234'}
      ]
    };
  }
  render() {
    return (
      <div>
        <h1>
          Ja<span className="highlight">mmm</span>ing
        </h1>
        <div className="App">
          <SearchBar />
          <div className="App-playlist">
            <SearchResults searchResults={this.state.searchResults} />
            <Playlist />
          </div>
        </div>
      </div>
    );
  }
}

export default App;

Playlist.js里面我有这个:

class Playlist extends React.Component {
  render() {
    return (
      <div className="Playlist">
        <input defaultValue={'New Playlist'} />
        <Tracklist />
        <a className="Playlist-save"></a>
      </div>
    );
  }
}

export default Playlist;

现在,我可以通过SearchResults组件传递道具道具,并传递到Tracklist组件。但是,我在尝试映射曲目道具时遇到错误:

TypeError: Cannot read property 'map' of undefined

当我从App文件中删除播放列表组件时,错误会自行修复。我在主<Playlist />文件中放入App.js时,我不确定为什么会收到错误。有人可以帮我理解吗?

这就是Tracklist.js的样子:

class Tracklist extends React.Component {
  constructor(props){
    super(props);
  }
  render() {
    return (
      <div className="TrackList">
        {this.props.tracks.map(track => <Track track={track} key={track.id} />)}
      </div>
    );
  }
}

export default Tracklist;

1 个答案:

答案 0 :(得分:0)

Playlist呈现Tracklist,它需要tracks道具。

尝试:

class Playlist extends React.Component {
  render() {
    return (
      <div className="Playlist">
        <input defaultValue={'New Playlist'} />
        <Tracklist tracks={[]} />
        <a className="Playlist-save"></a>
      </div>
    );
  }
}

查看错误是否消失。