对象作为 React 子对象无效 - 找到:带有键的对象

时间:2021-02-16 08:49:26

标签: reactjs react-hooks use-state

我尝试设置状态,但它不接受我从 URL 获取的 JSON 响应。但响应看起来不错,它是一个对象数组:

{"songs": 
  [
     {"id":1,"name":"Hello","singer":"Adele","img":"adele.png","type":"pop","mp3":"Adele.mp3"}, 
     {"id":2,"name":"de una vez","singer":"Selena gomez","img":"selena.png","type":"pop","mp3":"Selena.mp3"}, 
     {"id":3,"name":"Bayda","singer":"Navid","img":"navid.png","type":"pop","mp3":"Navid.mp3"}, 
     {"id":4,"name":"Takin' Back My Love ","singer":"Enrique Iglesias","img":"enrique.png","type":"Pop","mp3":"Enrique.mp3"}
  ]
}

这是我的反应组件:

import React, {useState, useEffect} from "react";

const App = () => {
  const [songs, setSongs] = useState([]);
  const [playing, setPlaying] = useState({});

  useEffect(() => {
    fetch(`http://localhost:8765`)
    .then(res => res.json())
    .then(jsonRes => {
      
      // setPlaying(jsonRes[0]);
      setSongs(jsonRes.songs);
      // jsonRes.songs.map(song => setSongs([...song]))
      console.log('Songs are: ', jsonRes.songs);
    });
    
  }, []);
  // console.log('songs:', songs)
  // console.log('playing:', playing)
  return (
    <div>
      Hello from App Songs: {songs}
    </div>
  );
}

export default App;

2 个答案:

答案 0 :(得分:1)

您应该使用 map 在 React 中显示数组。

阅读更多:https://reactjs.org/docs/lists-and-keys.html

答案 1 :(得分:0)

这个歌曲数组是一个对象数组,你不能将它传递给 return 语句。如果你想在你的return语句中有if你需要做的内容,比如你想显示每首歌的名字:

{songs.map(song => {
        return (
          <div>{song.name}</div>
        )
      })}