gpt4 book ai didi

javascript - 尝试 .map() 通过 props 传递的数组时出现 TypeError : Cannot read property 'map' of undefined,

转载 作者:行者123 更新时间:2023-11-28 03:52:43 26 4
gpt4 key购买 nike

我不确定为什么会收到 TypeError: Cannot read property 'map' of undefined here:

我正在尝试将数组从 App.js 传递到 => SearchResult.js 到 => TrackList.js

TrackList.js:

import React from 'react';
import Track from '../Track/Track'
import '../TrackList/TrackList.css';

class TrackList extends React.Component {
render() {
return (
<div className="TrackList">
{this.props.tracks.map(track => {
console.log(track);
<Track track={track} />}
)}
</div>
);
}
}

export default TrackList;

上面的 console.log(track) 按预期返回一个对象数组,我认为这确保了 this.props.tracks 是一个数组。

应用程序.js:

import React, { Component } from 'react';
import './App.css';
import SearchBar from './Components/SearchBar/SearchBar';
import SearchResults from './Components/SearchResults/SearchResults';
import Playlist from './Components/Playlist/Playlist';

const track = {
name: "Tiny Dancer",
artist: 'Elton John',
album: 'Madman Across The Water'
};

const tracks = [track, track, track];

class App extends Component {
constructor (props) {
super(props);
this.state = {'searchResults': tracks};
}
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;

搜索结果.js:

import React from 'react';
import '../SearchResults/SearchResults.css';
import TrackList from '../TrackList/TrackList';


class SearchResults extends React.Component {
render() {
return (
<div className="SearchResults">
{/* {console.log(this.props.searchResults)} */}
<h2>Results</h2>
<TrackList tracks={this.props.searchResults}/>
</div>
);
}
}

export default SearchResults;

我还尝试使用 props 从 App.js 传递数组(而不是状态),但我得到了相同的错误。

最佳答案

有时,React 会在加载 Prop 之前渲染应用程序。如果您从 api 调用获取 props,这种情况尤其会发生。如果发生这种情况,react 会抛出错误。这是一个解决方法:

import React from 'react';
import Track from '../Track/Track'
import '../TrackList/TrackList.css';

class TrackList extends React.Component {
constructor(props){
super(props)
this.state={}
}
render() {
//es6 syntax. this will allow the app to render and then replace the
//tracks variable with this.props.tracks when the props are ready
//this check if this.props.tracks exist and if it doesn't it will
//assign the variable to an empty array. then .map will not be
//called on an undefined variable.
let tracks = this.props.tracks ? this.props.tracks : [];
return (
<div className="TrackList">
{tracks.map(track => {
console.log(track);
<Track track={track} />}
)}
</div>
);
}
}

export default TrackList;

关于javascript - 尝试 .map() 通过 props 传递的数组时出现 TypeError : Cannot read property 'map' of undefined,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47840574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com