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

Chr*_*ott 3 javascript state destructuring reactjs

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

Run Code Online (Sandbox Code Playgroud)

我可以在哪里解构或者如何解决这个问题?

ray*_*eld 5

您可以使用可选链接和/或nullish coelescing 运算符来解决它。

\n

注意:IE 不支持其中任何一个但 babel 会对它们进行填充。

\n
const { name } = calledObj?.person ?? {};\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  1. 如果未定义,可选链接(?.in calledObj?.person)可以防止它爆炸calledObj
  2. \n
  3. 如果不存在,则空合并运算符 ( ??) 返回。{}calledObj.person
  4. \n
\n

通过这种组合,右侧可以保证评估为对象,因此左侧的解构永远不会爆炸。

\n

\r\n
\r\n
let calledObject; // undefined;\n\n// name is undefined, but it doesn\'t blow up.\nconst { name: name1 } = calledObject?.person ?? {};\n\nconsole.log(`name 1: ${name1}`); // name 1: undefined\n\n// ----------------\n\n// now it\'s an object, but doesn\'t have a person property\ncalledObject = {};\n\n// name is still undefined, still doesn\'t blow up.\nconst { name: name2 } = calledObject?.person ?? {};\n\nconsole.log(`name 2: ${name2}`); // name 1: undefined\n\n// ----------------\n\n// with person.name present\xe2\x80\xa6\ncalledObject.person = { name: \'joe\' };\n\nconst { name: name3 } = calledObject?.person ?? {};\n\n// \xe2\x80\xa6it works as you\'d expect\nconsole.log(`name 3: ${name3}`); // name 3: \'joe\'
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n