发送请求后如何实时模拟?

时间:2020-05-03 22:44:12

标签: javascript reactjs react-native redux react-redux

我有一个歌曲列表,当我单击其中的任何一个时,我打开播放器模态,然后发送请求以增加对此歌曲的计数视图, 同时,我在详细的歌曲中显示了计数视图,但它呈现了上一个最后的计数

例如, 我发送请求后,这首歌有30次观看,应该是31次, 但这仍然是30首歌曲的详细信息

那么有没有办法使其成为实时的?

代码

只说明一下 我从API获取歌曲,然后将其传递给操纵函数, 然后将其保存为状态,在用户单击列表中的任何歌曲之后,我将调度一个操作,将所有列表保存在redux存储中,

减速器

let initialState = {
  allSongs: [],
  currentIndex: 0,
};

const songsInPlayerReducer = (state = initialState, action) => {
  switch (action.type) {
    case SONGS_IN_PLAYER:
      return {
        ...state,
        allSongs: action.songs,
        currentIndex: action.index,
      };


    default:
      return state;
  }
};

export default songsInPlayerReducer;

动作

export const saveSongsPlayer = (songs, index) => {
  return {
    type: SONGS_IN_PLAYER,
    songs,
    index,
  };
};

主屏幕(从API获取歌曲)

manipulateArray = async array => {
    let songs = [];
    array.map(track =>
      songs.push({
        id: track.id,
        name: track.name,
        countview: track.countview,
        url: this.state.url + track.sounds,
        img: this.state.url + track.avatar,
      }),
    );

    return songs;
  };

getRecentSongs = async () => {
    try {
      let response = await API.get('/index');

      let {recent_tracks} = response.data.data;
      let recent_songs = await this.manipulateArray(recent_tracks);


      this.setState({

        recent_songs,

        loading: true,
      });
    } catch (error) {
      console.log(error);
      this.setState({error: true});
    }
  };


// Here a function I call after I press to any song in List 

playSong = index => {
    this.props.saveSongs(this.state.recent_songs, index);

  };

音乐播放器组件//我只是渲染计数视图(来自redux存储),然后向API发送请求以增加歌曲视图

incremntSongView = async () => {
    const {songs, currentIndex} = this.props;
    let id = songs[currentIndex].id;
    try {
      await API.post('/increnentView', {
        id,
      });
      console.log('increment Done');
    } catch (err) {

      console.log(err);
    }
  };

  onLoad = data => {
    this.setState(
      {
        duration: Math.floor(data.duration),
        loading: false,
      },
      () => this.incremntSongView(),
    );

  }


<Text>
     {this.props.songs[this.props.currentInx].countview}
</Text>

0 个答案:

没有答案