使用map()
函数与ReactJS一起使用时,我遇到了奇怪的问题。我将3个对象的数组硬编码到我的App状态,当我尝试迭代每个对象时,我可以在控制台中看到数据。看起来TrackList.js
再次呈现,然后吐出未定义的错误
这是我的主要文件:
App.js
:
import React, { Component } from 'react';
import './App.css';
import SearchBar from '../SearchBar/SearchBar';
import SearchResults from '../SearchResults/SearchResults';
import Playlist from '../Playlist/Playlist';
// import songs from './songs.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {
searchResults: [
{
"id": 1,
"name": "Roses",
"artist": "The Chainsmokers",
"album": "Unknown",
"isRemoval": false
},
{
"id": 2,
"name": "Fight Song",
"artist": "Rachel Platten",
"album": "None",
"isRemoval": false
},
{
"id": 3,
"name": "Thunder",
"artist": "Imagine Dragons",
"album": "Evolve",
"isRemoval": false
}
]
};
}
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;
Searchresults.js
:
import React from 'react';
import './SearchResults.css';
import TrackList from '../TrackList/TrackList';
class SearchResults extends React.Component {
render() {
return (
<div className="SearchResults">
<h2>Results</h2>
<TrackList tracks={this.props.searchResults} />
</div>
);
}
}
export default SearchResults;
TrackList.js
:
import React from 'react';
import './TrackList.css';
import Track from '../Track/Track';
class TrackList extends React.Component {
render() {
return (
<div className="TrackList">
{console.log("Tracks:")}
{console.log(this.props.tracks)}
{
this.props.tracks.map(track => {
return <Track track={track} key={track.id} />;
})
}
</div>
);
}
}
export default TrackList;
Track.js
:
import React from 'react';
import './Track.css';
class Track extends React.Component {
constructor(props) {
super(props);
this.renderAction = this.renderAction.bind(this);
}
renderAction(isRemoval) {
if (isRemoval) {
return "-";
}
return "+";
}
render() {
return (
<div className="Track">
<div className="Track-information">
{console.log("Each track:")}
{console.log(this.props.track)}
<h3>{this.props.track.name}</h3>
<p>{this.props.track.artist} | {this.props.track.album}</p>
</div>
<a className="Track-action">{this.renderAction(this.props.track.isRemoval)}</a>
</div>
);
}
}
export default Track;
Console.log()
:
Tracks:
Array [ {…}, {…}, {…} ]
Each track:
Object { id: 1, name: "Roses", artist: "The Chainsmokers", album: "Unknown" }
Each track:
Object { id: 2, name: "Fight Song", artist: "Rachel Platten", album: "None" }
Each track:
Object { id: 3, name: "Thunder", artist: "Imagine Dragons", album: "Evolve" }
Tracks:
undefined
TypeError: this.props.tracks is undefined
答案 0 :(得分:1)
尝试使用以下行替换this.props.tracks.map(track => {
行
this.props.tracks && this.props.tracks.map(track => {
// code continues