小编Chr*_*ott的帖子

如何解构存储为状态值的对象

在 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)

javascript state destructuring reactjs

3
推荐指数
1
解决办法
1024
查看次数

标签 统计

destructuring ×1

javascript ×1

reactjs ×1

state ×1