使用 "curly braces method" 解构从 API 调用中获取的嵌套对象

Destructuring the nested objects fetched from an API call using "curly braces method"

我是这样获取数据的:

  constructor(){
    super();    
    this.state = {
      fetchedData : [] 
    }
  }
  componentDidMount(){
    fetch("https://api.randomuser.me")
          .then(response => response.json())
          .then(data => {            
            this.setState({
                  fetchedData : data.results[0]
                          })
                              });                                                                                                                                     
  }

通过 this.state.fetchedData 获得此结果:

然后尝试了以下代码来解构结果:

render(){    
let {name} = this.state.fetchedData;

它工作正常,我用 console.log(name) 得到了以下结果:

所以我想进一步向下移动嵌套对象,但是当我尝试以下代码时:

render(){    
    let {name:{first, last, title}} = this.state.fetchedData;

它给了我以下错误:

您这里的类型不匹配。您正在用空数组初始化 fetchedData,然后期望它具有属性 firstlasttilte.

您应该使用有效条目而不是空数组进行初始化:

constructor(){
    super();    
    this.state = {
      fetchedData : {name: {first: '', last: '', title: ''}}
    }
  }

此外,由于异步请求,这是需要的。稍后调用相应的 then 处理程序 (this.setState({fetchedData:...}))。因此,您的组件将在 setState 调用之前以其初始值呈现。