我有一种情况,我应该通过id获得一首歌曲,以获得该歌曲的路径,然后点击按钮导航到该歌曲.
是否有任何特定的钩子可用于在数据到达时导航,useEffect将在任何时候状态改变时被调用,但问题是首先需要调度操作以获取歌曲,判断它是否返回任何项,然后导航.通常,如果它已经发布在列表上,则它应该存在于数据库中,但问题可能出在API端,因此判断results.length > 0
就是为什么需要该判断.
useEffect(() => {
const handleClick = (myId: string) => {
dispatch(SongActions.searchSong(myId));
if (results.length > 0) {
if (Object.keys(results[0]).length > 0) {
// navigate(`/songs/${results[0].myPath}`);
}
}
}
}, [dispatch, results])
当用户点击具有歌曲标题的列表项时,它应该以歌曲的id为参数来调用函数handleClick(id)
,即获取歌曲的元数据、源路径等.
<Typography onClick={() => handleClick(songItem.songId)} sx={styles.songListItemText}>{songItem.Title}</Typography>
编辑
这就是我如何设置searchSong
动作的:
searchSong: (obj: SearchSongInputModel): AppThunk<SearchPayload> => async (dispatch) => {
dispatch({
payload: { isLoading: true },
type: SearchActionType.REQUEST,
});
try {
const response = await SearchApi.searchSongAsync(obj);
if (response.length === 0) {
toast.info(`No data found: ${obj.SongId}`)
}
dispatch({
type: SearchActionType.RECEIVED_SONG,
payload: { results: response },
});
} catch (e) {
console.error("Error: ", e);
}
}