【问题标题】:How to destructure an object that is stored as a state value如何解构存储为状态值的对象
【发布时间】: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


    【解决方案1】:

    您可以使用optional chaining 和/或nullish coelescing operator 来解决它。

    注意:IE 不支持 eitherthese,但 babel 会填充它们。

    const { name } = calledObj?.person ?? {};
    
    1. 如果 calledObj 未定义,可选链接(calledObj?.person 中的 ?.)可防止其爆炸。
    2. 如果calledObj.person 不存在,无效的合并运算符 (??) 将返回 {}

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

    let calledObject; // undefined;
    
    // name is undefined, but it doesn't blow up.
    const { name: name1 } = calledObject?.person ?? {};
    
    console.log(`name 1: ${name1}`); // name 1: undefined
    
    // ----------------
    
    // now it's an object, but doesn't have a person property
    calledObject = {};
    
    // name is still undefined, still doesn't blow up.
    const { name: name2 } = calledObject?.person ?? {};
    
    console.log(`name 2: ${name2}`); // name 1: undefined
    
    // ----------------
    
    // with person.name present…
    calledObject.person = { name: 'joe' };
    
    const { name: name3 } = calledObject?.person ?? {};
    
    // …it works as you'd expect
    console.log(`name 3: ${name3}`); // name 3: 'joe'

    【讨论】:

      【解决方案2】:

      根据您希望 name 变量在首次渲染时默认设置的内容,我想您可以执行以下操作:

        const { name } = calledObj.person ? calledObj.person : {name: ''}
      

      【讨论】:

      • 这也有效,但如果您最终需要从对象中抓取大量物品,则可能会有点长。
      • @ChrisScott 我的意思是将{name: ''} 更改为{},您将得到与您接受的答案相同的结果。我只是把它放在那里,所以你可以在加载 useEffect 时选择将 name 设置为某个默认值而不是 undefined
      【解决方案3】:

      您可以使用以下方式初始化您的状态:

      const [calledObj, setCalledObj] = useState({person: {}})
      

      这会将undefined 放在“名称”中,但不会破坏您的代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        • 1970-01-01
        • 1970-01-01
        • 2012-03-11
        • 1970-01-01
        • 2019-12-01
        相关资源
        最近更新 更多