能否在Redux Store存储URL对象?报错及解决方案咨询
解决Redux存储URL对象的非序列化报错问题
Redux要求状态必须是可序列化的JS基础类型或普通对象/数组,URL实例属于不可序列化的复杂对象,因此会触发A non-serializable value was detected in the state报错。以下是几种修复方案:
方案一:存储URL字符串
将URL对象转换为字符串存入状态,使用时再重构为URL对象:
// 存入状态时 const url = new URL('https://example.com'); dispatch(setUrl(url.toString())); // 从状态取出使用时 const urlStr = useSelector(state => state.url); const urlObj = new URL(urlStr);
方案二:存储URL的结构化属性
提取URL的核心属性(如协议、主机、路径等)存为普通对象,需要时拼接重构:
// 存入状态时 const url = new URL('https://example.com/path?foo=bar'); dispatch(setUrl({ protocol: url.protocol, host: url.host, pathname: url.pathname, search: url.search })); // 从状态取出使用时 const urlData = useSelector(state => state.url); const urlObj = new URL(`${urlData.protocol}//${urlData.host}${urlData.pathname}${urlData.search}`);
方案三:关闭非序列化检查(不推荐)
若业务场景必须存储URL对象,可在Redux配置中关闭序列化检查,但会导致状态无法正常持久化、DevTools调试异常等问题:
import { configureStore } from '@reduxjs/toolkit'; const store = configureStore({ reducer: rootReducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: false, }), });
内容的提问来源于stack exchange,提问作者Rajat Jain
相关产品推荐
相关产品推荐

