我试图通过道具将状态呈现给嵌套组件。这就是我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;
答案 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>
);
}
}
查看错误是否消失。