我正在关注关于React Hooks的ReactJS教程。我试图从用户那里获取并显示输入名称,但是键入两个字符后,我的应用程序崩溃,错误为“ TypeError:无法读取null的属性'value'”
import React, { useState } from 'react';
function HookCounterTwo(props) {
const initialName = {
firstName: '',
lastName: ''
};
const [name, setName] = useState(initialName);
const changename = (e) => {
setName(prevName=>({...prevName, firstName: e.target.value}));
}
return (
<div>
{name.firstName}
<input type='text' value={name.firstName} onChange={e=>changename(e)} />
</div>
);
}
export default HookCounterTwo;
以下是日志:
HookCounterTwo.js:11 Uncaught TypeError: Cannot read property 'value' of null
at HookCounterTwo.js:11
at basicStateReducer (react-dom.development.js:15013)
at updateReducer (react-dom.development.js:15135)
at updateState (react-dom.development.js:15237)
at Object.useState (react-dom.development.js:15949)
at useState (react.development.js:1497)
at HookCounterTwo (HookCounterTwo.js:8)
at renderWithHooks (react-dom.development.js:14803)
at updateFunctionComponent (react-dom.development.js:17034)
at beginWork (react-dom.development.js:18610)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at beginWork$1 (react-dom.development.js:23203)
at performUnitOfWork (react-dom.development.js:22154)
at workLoopSync (react-dom.development.js:22130)
at performSyncWorkOnRoot (react-dom.development.js:21756)
at react-dom.development.js:11089
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
at flushSyncCallbackQueue (react-dom.development.js:11072)
at flushPendingDiscreteUpdates (react-dom.development.js:21847)
at flushDiscreteUpdates (react-dom.development.js:21827)
at finishEventHandler (react-dom.development.js:764)
at batchedEventUpdates (react-dom.development.js:798)
at dispatchEventForLegacyPluginEventSystem (react-dom.development.js:3568)
at attemptToDispatchEvent (react-dom.development.js:4267)
at dispatchEvent (react-dom.development.js:4189)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at discreteUpdates$1 (react-dom.development.js:21887)
at discreteUpdates (react-dom.development.js:806)
at dispatchDiscreteEvent (react-dom.development.js:4168)
我刚开始使用React,所以我可能会缺少一些概念。谢谢