如何检查收藏夹列表中的项目 - redux? [英] How to check item in favorite list - redux?

查看:44
本文介绍了如何检查收藏夹列表中的项目 - redux?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个功能,

1- 将歌曲添加到收藏列表:我向端点发送了一个请求,该请求将一首歌曲添加到用户最喜欢的列表中,它根据我在正文请求中传递的 song_id 添加歌曲.

1- Add Song to favorite List: I send an request to endpoint that's add a song to user favorite list, its add song based on song_id I passed in body request.

2- 从收藏列表中删除歌曲:与上一首相同,但根据 Song_id 从收藏夹列表中删除歌曲.

2- Remove Song from the favorite list: as previous but remove song from a favorite list based on song_id.

所以在播放器组件中,我有一个称为函数的心形图标,当用户点击它时,我调用它添加一首歌曲,否则我调用删除这首歌.

So in Player Component, I have a heart Icon that's called functions it's when users click on it i call to add a song, else i call to remove the song.

所有这些东西都可以在没有 redux 的情况下工作!

All these stuff work without redux!

所以我想保存song_id并根据它我想添加一个检查器,如果这个song_id存在,这意味着当用户点击它时,这首歌在心形图标将被填满"之前在最喜欢的列表中我想删除这首歌来自收藏夹列表所以我调用第二个函数向服务器发送请求等等.

So I want to save song_id and bassed on it i want to add a checker if this song_id exist that's mean this song is in a favorite list before "heart icon will be is fulled" when user click on it I want to remove this song from favorite list So I call the second function To send a request to server and so on.

所以我为此案例制作了一个动作/减速器,但我认为它不太好.

So i make an action/reducer for this case but i think it's not well.

UI播放器组件"-没有redux"

UI "Player Component" - "without redux"

  addToFavorite = async () => {
    const {tunes, token, currentTrackIndex} = this.state;
    this.setState({isFavorite: true});
    let id = tunes[currentTrackIndex].id;
    try {
      let AuthStr = `Bearer ${token}`;
      const headers = {
        'Content-Type': 'application/json',
        Authorization: AuthStr,
      };
      let response = await API.post(
        '/btn_add_favourite',
        {
          id,
        },
        {
          headers: headers,
        },
      );
      if (response.data.status === 'success') {
        alert('added');
      } else {
        alert('already exist');
      }
    } catch (err) {
      this.setState({isFavorite: false});
      console.log(err);
    }
  };

  deleteFromFavorite = async () => {
    const {tunes, token, isFavorite, currentTrackIndex} = this.state;

    let id = tunes[currentTrackIndex].id;
    console.log(tunes[currentTrackIndex]);
    try {
      let AuthStr = `Bearer ${token}`;
      const headers = {
        'Content-Type': 'application/json',
        Authorization: AuthStr,
      };
      if (isFavorite) {
        let response = await API.post(
          '/favourite_delete',
          {
            tracks_id: id,
          },
          {
            headers: headers,
          },
        );
        if (response.status === 200) {
          alert('song deleted from your favorite list');
          this.setState({isFavorite: false});
        }
        console.log(response);
      }
    } catch (err) {
      console.log(err);
    }
  };



   <Button
              onPress={() =>
                this.state.isFavorite // Not using redux yet so by default false
                  ? this.deleteFromFavorite()
                  : this.addToFavorite()
              }
              transparent
              style={styles.btnTransparent}>
              <Icon
                style={styles.iconColor}
                type="MaterialIcons"
                name={this.state.isFavorite ? 'favorite' : 'favorite-border'}
              />
            </Button>

Redux 的东西

动作/isFavoriteAction.js

Action/isFavoriteAction.js

import {ADD_TO_FAVORITE, REMOVE_FROM_FAVORITE} from './types';

export const addToFavoriteFunction = isFavorite => {
  return {
    type: ADD_TO_FAVORITE,
    payload: isFavorite,
  };
};

export const removeFromFavoriteFunction = isFavorite => {
  return {
    type: REMOVE_FROM_FAVORITE,
    payload: isFavorite,
  };
};

reducer/isFavorite.js

reducer/isFavorite.js

import {ADD_TO_FAVORITE, REMOVE_FROM_FAVORITE} from '../actions/types';

let initial_state = {
  isFavorite: false,
};

const isFavoriteReducer = (state = initial_state, action) => {
  switch (action.type) {
    case ADD_TO_FAVORITE:
      state = {
        ...state,
        isFavorite: true,
      };
      break;
    case REMOVE_FROM_FAVORITE:
      state = {
        ...state,
        isFavorite: false,
      };
      break;
    default:
      return state;
  }
  return state;
};

export default isFavoriteReducer;

推荐答案

特别是reducer部分,我看到你在为一首歌曲创建一个状态,我建议你在Redux中有完整的歌曲列表,然后你可以这样处理:

Specifically for the reducer part, I see you are creating a state for a single song, I would recommend you to have the full list of songs in Redux, then you can handle it this way:

import { ADD_TO_FAVORITE, REMOVE_FROM_FAVORITE } from "../actions/types";

let initialState = [];

/**
 *
 * @param {Array<Object>} songs A list of songs, this should be your state
 * @param {boolean} flag The boolean value, to fav or unfav a song
 * @return A new list of songs, with the updated isFavorite field for the song
 */
const updateSongFavoriteFlag = (songs, songId, flag) =>
    songs.map(song => {
        if (song.id === songId) {
            return { ...song, isFavorite: flag };
        }
        return song;
    });

const isFavoriteReducer = (state = initialState, action = {}) => {
    const { payload, type } = action;
    switch (action.type) {
        case ADD_TO_FAVORITE: {
            // Returning a new state instead of just altering the selected item
            // Where payload is the id of the song you want to mark as favorite
            return updateSongFavoriteFlag(state, payload, true);
        }
        case REMOVE_FROM_FAVORITE:
            return updateSongFavoriteFlag(state, payload, false);
        default:
            return state;
    }
    return state;
};

export default isFavoriteReducer;

这篇关于如何检查收藏夹列表中的项目 - redux?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆