英文:
How to store the value of useRef() in redux, when it references an audio tag
问题
我正在开发一个音频应用,类似于Spotify。
在我的App.jsx中,我创建了一个audioRef,并将其用于引用HTML音频元素:
const audioRef = useRef()
<audio ref={audioRef} />
我想要使用redux-toolkit将audioRef存储在Redux中,以便在全局范围内访问。
我尝试这样做:
useEffect(() => {
dispatch(setAudioRef(audioRef));
}, []);
其中setAudioRef是:
setAudioRef(state, action) { state.audioRef = action.payload; },
不幸的是,我收到以下错误消息:
在操作中检测到了一个不可序列化的值,路径为:'payload'。
audioRef被应用中的许多不同组件使用,用于检查播放/暂停音频、访问已经过的时间、持续时间等等。
非常感谢任何建议!
英文:
I am building an audio app, something like Spotify.
In my App.jsx, I create an audioRef and use it to reference to the html audio element:
const audioRef = useRef()
<audio ref={audioRef} />
I would like to store the audioRef in Redux with redux-toolkit, to make it accessible globally.
I tried doing it like so:
useEffect(() => {
dispatch(setAudioRef(audioRef));
}, []);
where setAudioRef is:
setAudioRef(state, action) { state.audioRef = action.payload; },
Unfortunately, I get the following error message:
A non-serializable value was detected in an action, in the path: 'payload'.
The audioRef is used by many different components across the app to check play/pause the audio, access time elapsed, duration, etc.
Any tips would be greatly appreicated!!
答案1
得分: 1
不。音频对象不是“数据”或“状态”,不可序列化,因此不应放入Redux存储:
https://redux.js.org/style-guide/#do-not-put-non-serializable-values-in-state-or-actions
更好的选项是在组件树的根附近使用上下文提供程序和useState
,然后将其放在那里。
英文:
Don't. An audio object isn't data or state, and it's not serializable, so it doesn't belong in the Redux store:
https://redux.js.org/style-guide/#do-not-put-non-serializable-values-in-state-or-actions
A better option would be to have a context provider + a useState
near the root of the component tree, and put it in there.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论