@Speakermen

Как в reducerе обратиться к другому reducerу?

Постоянная ошибка думаю что делаю что-то не то(

stackblitz

A non-serializable value was detected in the state, in the path: `playlist.trackService`. Value:
TrackService{}

Take a look at the reducer(s) handling this action type: playlist/playAudio.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)


Как обратиться к playAudio?
const playlistSlice = createSlice({
  name: 'playlist',
  initialState,
  reducers: {
    playAudio: (state, action) => {
      if (!state.flag) {
        state.flag = true;
        state.track = state.trackService.findOne(action.payload);
        state.audio.src = state.track.audioPath;
        state.audio.play();
      }

      state.audio.play();
    },
    pauseAudio: (state) => {
      state.audio.pause();
    },
    nextAudio: (state) => {
      state.id++;
      if (state.id > state.trackService.findAll().length - 1) {
        state.id = 0;
      }
      state.flag = false;
      name.playAudio; //как обратиться к playAudio?
    },
    prevAudio: (state) => {
      state.id--;
      if (state.id < 0) {
        state.id = state.trackService.findAll().length - 1;
      }
      state.flag = false;
      name.playAudio;
    },
  },
});


//slices/playlistSlice.js
import { createSlice } from '@reduxjs/toolkit';

class TrackDto {
  id = 0;
  author = '';
  audioName = '';
  audioPath = '';
  currentTime = '';
  duration = '';
  image = '';
}

class TimeDto {
  currentTime = 0;
  duration = 0;
}

class TrackService {
  #state = [];

  constructor() {
    this.#state = [
      {
        id: 1,
        author: 'Santo Beats feat FXKEMANE',
        audioName: 'Bounce',
        audioPath:
          'https://cdn.drivemusic.me/dl/online/koB-KiyPMOfUwkYEND5VQg/1698056654/download_music/2023/10/santo-beats-feat.-fxkemane-bounce.mp3',
        currentTime: '00:00',
        duration: '01:47',
        image: 'https://fakeimg.pl/384x384/',
      },
      {
        id: 2,
        author: 'DVRST',
        audioName: 'Your Name',
        audioPath:
          'https://cdn.drivemusic.me/dl/online/GnYXO4LFYr59eMeFg9hI1Q/1698065067/download_music/2023/05/dvrst-your-name.mp3',
        currentTime: '00:00',
        duration: '02:24',
        image: 'https://fakeimg.pl/384x384/',
      },
      {
        id: 3,
        author: 'Balance',
        audioName: 'Beneath My Shade',
        audioPath:
          'https://cdn.drivemusic.me/dl/online/txH1PR1FrGupM893CUsVQQ/1698065067/download_music/2023/05/beneath-my-shade-balance.mp3',
        currentTime: '00:00',
        duration: '02:12',
        image: 'https://fakeimg.pl/384x384/',
      },
      {
        id: 4,
        author: 'RAVE',
        audioName: 'Dxrk ダーク',
        audioPath:
          'https://lmusic.kz/files/mp3s/2022-05/Dxrk%20%E3%83%80%E3%83%BC%E3%82%AF%20-%20RAVE.mp3',
        currentTime: '00:00',
        duration: '02:49',
        image: 'https://fakeimg.pl/384x384/',
      },
      {
        id: 5,
        author: 'Prince of falls',
        audioName: 'Nightmare',
        audioPath:
          'https://ds.mzmdl.com/get/music/20211231/Prince_of_falls_-_Nightmare_73581644.mp3',
        currentTime: '00:00',
        duration: '03:11',
        image:
          'https://is1-ssl.mzstatic.com/image/thumb/Music116/v4/28/e1/90/28e1902a-e590-cde5-0923-3878b03b39a3/5059950094855_cover.jpg/400x400bb.jpg',
      },
    ];

    return this;
  }

  findAll() {
    return this.#state;
  }

  findOne(id) {
    return this.#state[id];
  }
}

const initialState = {
  id: 4,
  trackService: new TrackService(),
  tracks: null,
  track: null,
  flag: false,
  audio: new Audio(),
};

const playlistSlice = createSlice({
  name: 'playlist',
  initialState,
  reducers: {
    playAudio: (state, action) => {
      if (!state.flag) {
        state.flag = true;
        state.track = state.trackService.findOne(action.payload);
        state.audio.src = state.track.audioPath;
        state.audio.play();
      }

      state.audio.play();
    },
    pauseAudio: (state) => {
      state.audio.pause();
    },
    nextAudio: (state) => {
      state.id++;
      if (state.id > state.trackService.findAll().length - 1) {
        state.id = 0;
      }
      state.flag = false;
      name.playAudio;
    },
    prevAudio: (state) => {
      state.id--;
      if (state.id < 0) {
        state.id = state.trackService.findAll().length - 1;
      }
      state.flag = false;
      name.playAudio;
    },
  },
});

export const { playAudio, pauseAudio, nextAudio, prevAudio } =
  playlistSlice.actions;
export default playlistSlice.reducer;


//slices/index.js
import { configureStore } from '@reduxjs/toolkit';
import playlistReducer from './playlistSlice.js';

export default configureStore({
  reducer: {
    // Свойство counter будет внутри объекта общего состояния: state.counter
    playlist: playlistReducer,
  },
});


//App.js
import React from 'react';
import './style.css';
import { useSelector, useDispatch } from 'react-redux';
import {
  playAudio,
  pauseAudio,
  nextAudio,
  prevAudio,
} from './slices/playlistSlice.js';

export default function App() {
  // Вытаскиваем данные из хранилища
  // Здесь state — это все состояние
  //const count = useSelector((state) => state.playlist);
  // Возвращает метод store.dispatch() текущего хранилища
  const dispatch = useDispatch();

  console.log(useSelector((state) => state.playlist.id));

  return (
    <div>
      <div>
        <button onClick={() => dispatch(playAudio(4))}>playAudio</button>
        <button onClick={() => dispatch(pauseAudio())}>pauseAudio</button>
        <button onClick={() => dispatch(nextAudio())}>nextAudio</button>
        <button onClick={() => dispatch(prevAudio())}>prevAudio</button>
      </div>
    </div>
  );
}


import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import store from './slices/index.js';
import App from './App';

const root = createRoot(document.getElementById('app'));

root.render(
  <StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </StrictMode>
);
  • Вопрос задан
  • 147 просмотров
Решения вопроса 1
0xD34F
@0xD34F
Что имеет сказать на этот счёт документация:

The functions passed to the reducers parameter can be accessed through the caseReducers return field.

Так что

playlistSlice.caseReducers.playAudio(state, { payload: state.id });
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы