【发布时间】:2021-02-26 23:42:35
【问题描述】:
在 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
return (<div>{name}</div>)
}
我在哪里可以解构或如何解决这个问题?
【问题讨论】:
标签: javascript reactjs state destructuring