React 无法读取未定义的属性(读取 'map')
React Cannot read properties of undefined (reading 'map')
我在我的代码中收到此错误:“TypeError:无法读取未定义的属性(读取 'map')”,我完全不知道为什么,我似乎没有错误代码 IDE 本身,我已经检查了很多次
感谢阅读!
const { user } = useAuth0();
const [{songs, setSongs}] = useState([])
useEffect(() => {
if (user) {
const requestOptions = {
method: 'GET'
};
let url = 'https://present-deck.com/getsongs/' + user.sub
fetch(url, requestOptions)
.then(response => {
return response.json();
}).then(jsonResponse => {
setSongs(jsonResponse)
}).catch (error => {
console.log(error);
})
console.log(songs)
}
}, [user])
return (
<>
<ul>
{songs.map((el) => (
<li key={el} className="tailwindCssStuff"
onClick={ () => {if (listedSongs.indexOf(el.title) === -1){
addListedSongs(listedSongs.concat(el.title))}}}>
{el.title}</li>
))}
</ul>
</>
)
}```
const [{songs, setSongs}] = useState([])
应该是const [songs, setSongs] = useState([])
在解构你的状态时,你有一组不必要的大括号,这导致你的 songs
和 setSongs
成为 undefined
。
相反你想要:
const [songs, setSongs] = useState([])
我在我的代码中收到此错误:“TypeError:无法读取未定义的属性(读取 'map')”,我完全不知道为什么,我似乎没有错误代码 IDE 本身,我已经检查了很多次 感谢阅读!
const { user } = useAuth0();
const [{songs, setSongs}] = useState([])
useEffect(() => {
if (user) {
const requestOptions = {
method: 'GET'
};
let url = 'https://present-deck.com/getsongs/' + user.sub
fetch(url, requestOptions)
.then(response => {
return response.json();
}).then(jsonResponse => {
setSongs(jsonResponse)
}).catch (error => {
console.log(error);
})
console.log(songs)
}
}, [user])
return (
<>
<ul>
{songs.map((el) => (
<li key={el} className="tailwindCssStuff"
onClick={ () => {if (listedSongs.indexOf(el.title) === -1){
addListedSongs(listedSongs.concat(el.title))}}}>
{el.title}</li>
))}
</ul>
</>
)
}```
const [{songs, setSongs}] = useState([])
应该是const [songs, setSongs] = useState([])
在解构你的状态时,你有一组不必要的大括号,这导致你的 songs
和 setSongs
成为 undefined
。
相反你想要:
const [songs, setSongs] = useState([])