我想在另一个setState
函数中设置变量的状态。
我的代码是这样的:
const [songs, setSongs] = useState()
const [playlists, setPlaylists] = useState()
function async firstClick() {
function secondClick() {
songs = await fetch("/songs")
setSongs(songs)
}
setPlaylists(
<>
// other element that have trigger handleClick() on click
{songs}
</>
);
}
过程如下:
- 用户点击触发
firstClick()
的元素。 setPlaylists()
setplaylists
.- 用户点击从
setPlaylists()
设置的元素,触发secondClick()
。 secondClick()
setsongs
.playlists
中的songs
没有更新,因为状态已经更新。
对于这种情况是否有React模式?如何设置songs
的状态,并使其在setPlaylists()
的状态下更新。
const updatedSongs = async () => {
songs = await fetch("/songs")
setSongs(songs)
}
function handleClick() {
updatedSongs()
}
useEffect(() => { updatedSongs() },[])