【发布时间】:2021-10-11 01:54:16
【问题描述】:
我想最初用“状态”中可用的全名值填充输入字段。但是当我重新加载页面时出现TypeError: Cannot read property 'fullname' of null 错误,因为当时尚未加载状态。
function EditProfile(){
const {state,dispatch}= useContext(UserContext); //line 1
const [fullname, setFullname]= useState(state.fullname); //line 2
return(
<input type="text" placeholder="Name" value={fullname}></input>
)
}
我尝试像这样更改第 2 行:
const [fullname, setFullname]= useState(state?state.fullname:"");
这次我没有收到任何错误。但输入字段包含空字符串而不是state.fullname 值。
我希望在为全名定义 useState(第 2 行)之前完全加载状态(第 1 行)。
如何做到这一点?
【问题讨论】:
标签: reactjs use-state mern context-api use-context