I want to create next and back button for my music app with UseReduce and Usecontext but somethings is wrong. When I push the button the music change but in audio doesn't work. My codes are like this
我想为我的音乐应用程序创建下一个和后退按钮,但有些事情是错误的。当我按下按钮的音乐改变,但在音频不工作。我的代码是这样的
This one is my musicControl component :
这是我的musicControl组件:
import React, { useContext, useState } from 'react'
import GlobalContext from '../context/MainContext'
const MusicControl = () => {
const [control,setControl] = useState(true);
const {dispatch} = useContext(GlobalContext);
const handleControl = () => {
if (control) {
dispatch("PLAY_MUSIC");
setControl(false)
}
else {
dispatch("STOP_MUSIC");
setControl(true)
}
}
return (
<div className='flex w-full justify-evenly items-center mt-10 pb-[120px]'>
<button className='bg-black text-white px-4 py-2' onClick={async() => {await dispatch("BACK_SONG")}}>BACK</button>
<button className='bg-black text-white px-4 py-2' onClick={handleControl}>STOP/START</button>
<button className='bg-black text-white px-4 py-2' onClick={async () => {await dispatch("NEXT_SONG")}}>NEXT</button>
</div>
)
}
export default MusicControl
This one is my audio player components ;
这一个是我的音频播放器组件;
import React, { useContext} from 'react'
import GlobalContext from '../context/MainContext'
const Audio = () => {
const {song} = useContext(GlobalContext);
return (
<div className='hidden'>
<audio controls id='mainAudio'>
<source src={song} type="audio/ogg"></source>
</audio>
</div>
)
}
export default Audio
This one is useReduce Component ;
这是一个Use Reduce组件;
export const initialState = 0;
export const reducer = (state,action) => {
const audio = document.querySelector("#mainAudio");
switch(action) {
case "BACK_SONG":
audio.pause();
return state - 1
case "NEXT_SONG":
return state + 1
case "STOP_MUSIC":
audio.pause();
return state
case "PLAY_MUSIC":
audio.play();
return state
default:
return "";
}
}
And the last one is my contextAPI.
最后一个是我的上下文API。
import { createContext, useEffect, useReducer, useState} from "react";
import { initialState, reducer } from "./MainReducer";
import dream from '../assets/musics/dream.mp3'
import meta from '../assets/musics/meta.mp3'
const GlobalContext = createContext();
const songs = [dream,meta,dream,meta,dream,meta]
export function Provider({children}) {
const [count,dispatch] = useReducer(reducer,initialState)
const [song, setSong] = useState(dream);
useEffect(() => {
setSong(songs[count]);
},[count])
return (
<GlobalContext.Provider value={{song,dispatch}}>
{children}
</GlobalContext.Provider>
)
}
export default GlobalContext;
I don't understand what is wrong in my app. I have been strugling 3 hours and I couldn't fix. Thank you so much...
我不明白我的应用程序出了什么问题。我已经挣扎了3个小时,还是治不好。太感谢你了..。
更多回答
What do you mean by "audio doesn't work"? Have you try to debug your code?
你说的“音频不起作用”是什么意思?你试过调试你的代码吗?
我是一名优秀的程序员,十分优秀!