代码之家  ›  专栏  ›  技术社区  ›  Matt Saunders

反应未定义道具问题

  •  1
  • Matt Saunders  · 技术社区  · 8 年前

    我正在将道具对象传递给子组件。我遇到的问题是,有时一些嵌套值将为null或未定义,因此我得到了可怕的props undefined消息 Uncaught TypeError: Cannot read property 'xxx' of undefined

    据我所知 defaultProps 仅当props对象为null时触发,而不是仅当 一些 的值为空。

    示例:

    this.state {
        person: { 
            name: "Matt", 
            age: 34, 
            OtherDetails: { city:"", country: "" } 
        }
    }
    

    在上面的示例中,有时城市或国家值将为null或未定义。检查这些实例似乎非常困难和费力-当道具数据不完整且不可靠时,处理此类情况的最佳方法是什么?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Andrew Rosewarn    8 年前

    如果您的问题表明您只是试图将对象作为道具传递,然后访问组件中可能不存在的该对象的属性,那么您是否考虑过提供默认值?(假设您使用ES6语法)。

    我将在render方法中使用destructuring来访问我将在render方法中使用的每个属性,并为每个项目提供一个默认值,如下所示。

    class PersonComp extends React.Component {
        render() {
            const {
                name = '',
                age = 0,
                OtherDetails: {city = ''},
                OtherDetails: {country = ''}
    
            } = this.props.person;
    
            return (
                <div>
                    <div>{name}</div>
                    <div>{age}</div> 
                    <div>{city}</div>
                    <div>{country}</div>
                </div>
    
            )
        }
    }
    

    通过这样做,如果提供的数据中不存在城市或国家,则将创建这些城市或国家并为其分配空字符串的值。