ReactJS | 无法将未定义或空转换为对象(使用 Formik)
2021-01-09
1665
已修复:如果您不传递 InitialValues,即使不需要它们,Formik 显然也会生气。
我试图在 React 中编写一个 formik 表单,但每当我点击提交按钮时,都会遇到“TypeError:无法将未定义或 null 转换为对象”。有什么想法吗?
{(activeServers && Object.keys(activeServers).length > 0) && Object.keys(activeServers).map((key) => (
<div>
<li>{activeServers[key].robloxData.serverId} [Player count: {activeServers[key].robloxData.playerList.length}]</li>
<Formik onSubmit={() => {
if (!activeServers || !activeServers[key]) return;
shutdownServer(activeServers[key].robloxData.placeId, activeServers[key].robloxData.serverId);
}}>
{(props) => (
<form onSubmit={props.handleSubmit}>
<h1>Heyt</h1>
<Button type="submit" colorScheme="red" children="Shutdown Server" />
</form>
)}
</Formik>
</div>
))}
这是错误:
Uncaught TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at setNestedObjectValues (utils.ts:158)
at formikReducer (Formik.tsx:98)
at updateReducer (react-dom.development.js:15318)
at Object.useReducer (react-dom.development.js:16425)
at useReducer (react.development.js:1512)
at useFormik (Formik.tsx:173)
at Formik (Formik.tsx:994)
at renderWithHooks (react-dom.development.js:14985)
at updateFunctionComponent (react-dom.development.js:17356)
at beginWork (react-dom.development.js:19063)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
at invokeGuardedCallback (react-dom.development.js:4056)
at beginWork$1 (react-dom.development.js:23964)
at performUnitOfWork (react-dom.development.js:22776)
at workLoopSync (react-dom.development.js:22707)
at renderRootSync (react-dom.development.js:22670)
at performSyncWorkOnRoot (react-dom.development.js:22293)
at react-dom.development.js:11327
at unstable_runWithPriority (scheduler.development.js:646)
at runWithPriority$1 (react-dom.development.js:11276)
at flushSyncCallbackQueueImpl (react-dom.development.js:11322)
at flushSyncCallbackQueue (react-dom.development.js:11309)
at discreteUpdates$1 (react-dom.development.js:22420)
at discreteUpdates (react-dom.development.js:3756)
at dispatchDiscreteEvent (react-dom.development.js:5889)
2个回答
对于那些没有仔细阅读这篇文章的人(比如我自己),似乎作者自己就确定了解决方案。为了便于查看,
Formik
组件需要
initialValues
作为 prop,即使未使用也是如此。干杯!
qslabs
2021-06-17
看起来
activeServers
为空或未定义。试试这个
if ( activeServers !== null && activeServers !== undefined &&
typeof Object.keys(activeServers) !== "undefined" &&
Object.keys(activeServers).length > 0
) {
// execute your code now
}
Nooruddin Lakhani
2021-01-09