在 React App 组件中,我调用 API 并将响应存储在本地状态中。然后我想解构存储在该状态下的对象,但我不能只在 useEffect 下面解构,因为它会在调用完成之前抛出错误。
另外,我不想分解 useEffect 中的对象,因为我想要其他事情的完整响应。
这是一个例子:
const MyComponent = () => {
const [calledObj, setCalledObj] = useState({})
useEffect(() => {
//Calling API here and setting object response as calledObj State
setCalledObj(apiResponse)
}, []);
//This will throw an error when the API response has not been sent back yet.//
// While this would be easy to write the whole path in the return, the actual path is really long.//
const { name } = calledObj.person …Run Code Online (Sandbox Code Playgroud)