如何在React的setState钩子中使用另一个状态?



我想在另一个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}
</>
);
}

过程如下:

  1. 用户点击触发firstClick()的元素。
  2. setPlaylists()setplaylists.
  3. 用户点击从setPlaylists()设置的元素,触发secondClick()
  4. secondClick()setsongs.
  5. playlists中的songs没有更新,因为状态已经更新。

对于这种情况是否有React模式?如何设置songs的状态,并使其在setPlaylists()的状态下更新。

const updatedSongs = async () => {
songs = await fetch("/songs")
setSongs(songs)
}
function handleClick() {
updatedSongs()
}

useEffect(() => { updatedSongs() },[])

相关内容

最新更新