我浏览了关于如何在React中创建自定义提交警报的指南。在本指南中,我必须通过";提交";函数和";拒绝";通过州经理转到我的档案。但是,我们在react中使用了不同的状态管理器(他使用Context和I redux工具包(。所以问题是,我不能将函数作为值传递给我的存储(里面的所有值都必须是可序列化的(。
因此,我想序列化reject
和resolve
函数,并在一段时间后将它们恢复到正常状态。但我遇到的问题是,当我使用response.toString()
时,它返回=>function () { [native code] }
,当我尝试反序列化此函数时,它返回下一个错误:
Uncaught SyntaxError: Unexpected identifier 'code'
at new Function (<anonymous>)
at parseFunc (alert.ts:12:1)
at AlertHandler (AlertHandler.tsx:28:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateFunctionComponent (react-dom.development.js:19588:1)
at beginWork (react-dom.development.js:21601:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
我的代码:
export const serializeFunc = (func: Function) =>
func.toString()
export const parseFunc = (value: string) =>
// eslint-disable-next-line
new Function('return ' + value)()
// somewhere want to sequelize
{
resolve: serializeFunc(resolve),
reject: serializeFunc(reject)
}
// somewhere want to deserialize
const parsedReject = parseFunc(reject)
const parsedResolve = parseFunc(resolve)
问题是,此代码适用于正常函数(例如() => 2
(。我真的不知道问题出在哪里。有什么可能的解决方案吗?
所有代码(简化(:
export const serializeFunc = (func: Function) =>
func.toString()
export const parseFunc = (value: string) =>
// eslint-disable-next-line
new Function('return ' + value)()
export const useConfirm = () => {
const dispatch = useAppDispatch()
const Confirm = async (alert: CreateSubmitAlert) => {
const promise = new Promise<void>((resolve, reject: () => void) => {
const newAlert: IConfirmAlert = {
...alert,
resolve: serializeFunc(resolve),
reject: serializeFunc(reject)
}
dispatch(setAlert(newAlert))
})
return await promise.then(
() => true,
() => false
).finally(
() => dispatch(closeAlert())
)
}
return Confirm
}
我的警报本身:
const alert = useAppSelector(selectAlert)
if (alert !== undefined) {
const {
// ...
reject,
resolve
} = alert
const parsedReject = parseFunc(reject)
const parsedResolve = parseFunc(resolve)
return <>
<Button
onClick={() => parsedReject()}
className={styles.button}
buttonStyle={'ghost'}
>
{'Cancel'}
</Button>
<Button
onClick={() => parsedResolve()}
className={styles.button}
>
{confirmLabel}
</Button>
</>
}
可能无法序列化此[native code]
。所以我只是重新制作我的功能
const promise = new Promise<AlertResult<T>>((resolve, _reject) => {
store.dispatch(setAlert(alert))
store.subscribe(() => {
const result = selectAlertResult(store.getState())
if (result !== undefined) {
return resolve(result)
}
})
})
我订阅以存储此函数中的值更改。然后把它们还回去。现在我不存储函数,而是存储值。