如何将useRef()的值存储在Redux中,当它引用一个音频标签时

huangapple go评论70阅读模式
英文:

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()

&lt;audio ref={audioRef} /&gt;

I would like to store the audioRef in Redux with redux-toolkit, to make it accessible globally.

I tried doing it like so:

useEffect(() =&gt; {
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: &#39;payload&#39;.

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.

huangapple
  • 本文由 发表于 2023年2月18日 11:17:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定