【发布时间】: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