简体   繁体   English

React / Redux-使用Thunk将JSON数据从一个API调用传递到另一个Redux操作

[英]React/Redux - Passing JSON data from one API call to another Redux action using Thunk

I'm new to Redux and I am sending an API request to the Spotify API. 我是Redux的新手,正在向Spotify API发送API请求。 I am using Thunk and have an action called FetchCurrentlyPlaying which fetches the current song that is being played. 我正在使用Thunk,并有一个名为FetchCurrentlyPlaying的操作,该操作将提取正在播放的当前歌曲。

Within the JSON returned from this API call there is an id number which identifies the artist. 在从此API调用返回的JSON中,有一个标识艺术家的ID号。 When I retrieve this JSON data within FetchCurrentlyPlaying I want to then pass this id number to another Redux action, FetchAlbums. 当我在FetchCurrentlyPlaying中检索此JSON数据时,我想将此ID号传递给另一个Redux操作FetchAlbums。

FetchAlbums will then send another API request to the Spotify API and pass the URL the id of the currently playing artist. 然后,FetchAlbums将向Spotify API发送另一个API请求,并将当前正在播放的艺术家的ID传递给URL。 This will retrieve other albums by that artist. 这将检索该艺术家的其他专辑。

How do I pass the id from one action to another? 如何将ID从一个动作传递到另一个动作?

You can dispatch other actions from your thunk 您可以从重击中分派其他动作

const FetchAlbums = albumId => dispatch => axios(albumId)
  .then((data) => {
    dispatch(setAlbum(data));
  });

const FetchCurrentlyPlaying = song => dispatch => axios(song)
  .then((data) => {
    dispatch(setSong(data));
    dispatch(FetchAlbums(data.albumId));
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM