【问题标题】:Objects are not valid as a React child - found: object with keys对象作为 React 子项无效 - 找到:带键的对象
【发布时间】:2021-05-19 02:49:29
【问题描述】:

我尝试设置状态,但它不接受我从 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;

【问题讨论】:

  • 有什么问题?

标签: reactjs react-hooks use-state


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你应该使用map 在 React 中显示一个数组。

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

    【讨论】:

    • 我完全忘记了返回中的那个 {songs} 对象。非常感谢
    猜你喜欢
    • 2020-12-28
    • 2020-05-25
    • 2022-01-05
    • 1970-01-01
    • 2021-06-28
    • 2018-01-12
    • 2020-11-03
    • 2019-10-26
    • 2020-08-26
    相关资源
    最近更新 更多