无法使用挂钩映射获取的数据

时间:2020-10-23 19:55:21

标签: reactjs api react-hooks jsx

我尝试显示有关存储在音乐挂钩中的音乐的信息,浏览器抱怨显示此错误TypeError: Cannot read property 'map' of undefined

控制台向我显示已获取的数据。这是一个包含25个对象的数组。 我尝试了music.data && music.data.map

function App() {
  
  const [ playlist, setPlaylist ] = useState('beyonce')
  const [music, saveMusic ] = useState([])
  useEffect(() => {
    console.log('new playlist')
    fetch(`https://rapidapi.p.rapidapi.com/search?q=${playlist}`, {
          "method": "GET",
          "headers": {
            "x-rapidapi-host": "deezerdevs-deezer.p.rapidapi.com",
            
          }
        })
        .then(response => response.json())
        .then(json => saveMusic(json))
       
  
  }, [playlist])
  console.log(music)
  return (
    <div>
       <h2>useEffect practice</h2>
      <div>
       <button onClick={() => setPlaylist('beyonce')}>Playlist 1</button>
       <button onClick={() => setPlaylist('eminem')}>Playlist 2</button>
       <button onClick={() => setPlaylist('ac/dc')}>Playlist 3</button>
       </div>
       <div>
         <h5>{playlist}</h5>
        
         {music.data.map(i => {
           return (
             <>
                  <img style={{width: '100px'}} src={i.album.cover_big} />
                 <p>{i.title}</p>
             </>
           )
         })}
       </div>
    </div>
  );
}

export default App;

我尝试显示有关存储在音乐挂钩中的音乐的信息,浏览器抱怨显示此错误TypeError: Cannot read property 'map' of undefined

1 个答案:

答案 0 :(得分:1)

<html> <body> <button class="grey" value="ac"></button> <button class="grey" value="+/-"></button> <button class="grey" value="%"></button> <button class="coral" value="➗"></button> <button class="dark" value="7"></button> <button class="dark" value="8"></button> <button class="dark" value="9"></button> <button class="coral" value="X"></button> <button class="dark" value="4"></button> <button class="dark" value="5"></button> <button class="dark" value="6"></button> <button class="coral" value="-"></button> <button class="dark" value="1"></button> <button class="dark" value="2"></button> <button class="dark" value="3"></button> <button class="coral" value="+"></button> <button class="zero" value="0"></button> <button class="dark" value="."></button> <button class="coral" value="="></button> </body> <script src="yourjavascriptfile.js"></script> </html> var buttons = document.getElementsByTagName("button"); for (var i = 0; i < buttons.length; i++) { buttons[i].innerText = buttons[i].value; } 在第一个渲染器上不存在。您可以使用music.data初始化music

{ data: [] }

或者在尝试const [music, saveMusic ] = useState({ data: [] }) 之前检查music.data是否存在:

map

如果要确保{music.data && music.data.map(i => { return ( <> <img style={{width: '100px'}} src={i.album.cover_big} /> <p>{i.title}</p> </> ) })} 是一个数组,可以使用Array.isArray()